To check if a vector is not empty in R, you can use the length
function or the !is_empty
function from the purrr
package.
In this example,
num_vec
with several elements.length
function to check the length of num_vec
.num_vec
is greater than zero, it means the vector is not empty.num_vec <- c(10, 20, 30, 40, 50)
if (length(num_vec) > 0) {
print("Numeric vector is not empty")
} else {
print("Numeric vector is empty")
}
[1] "Numeric vector is not empty"
In this example,
char_vec
with several elements.purrr
package and its !is_empty
function to check if char_vec
is not empty.!is_empty(char_vec)
returns TRUE
, it means the vector is not empty.library(purrr)
char_vec <- c("apple", "banana", "cherry", "date")
if (!is_empty(char_vec)) {
print("Character vector is not empty")
} else {
print("Character vector is empty")
}
[1] "Character vector is not empty"
In this tutorial, we learned How to check if a Vector is Not Empty in R language with well detailed examples.