To check if a vector is empty in R, you can use the length
function or the is_empty
function from the purrr
package.
In this example,
num_vec
with no elements.length
function to check the length of num_vec
.num_vec
is zero, it means the vector is empty.num_vec <- numeric(0)
if (length(num_vec) == 0) {
print("Numeric vector is empty")
} else {
print("Numeric vector is not empty")
}
[1] "Numeric vector is empty"
In this example,
char_vec
with no elements.purrr
package and its is_empty
function to check if char_vec
is empty.is_empty(char_vec)
returns TRUE
, it means the vector is empty.library(purrr)
char_vec <- character(0)
if (is_empty(char_vec)) {
print("Character vector is empty")
} else {
print("Character vector is not empty")
}
[1] "Character vector is empty"
In this tutorial, we learned How to check if a Vector is Empty in R language with well detailed examples.