Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see whether a vector is empty in R

Tags:

First of all, I need to initialize an empty vector in R, Does the following work ?

vec <- vector()

And how I can evaluate whether vec is empty or not ?

like image 798
ToBeGeek Avatar asked Nov 19 '13 01:11

ToBeGeek


People also ask

How do you check if something is empty in R?

To check if list is empty in R programming, we have to evaluate the condition that the length of list is zero. Call length() function with this list passed as argument and if the return value is 0 using equal to operator.

How do I check if a character is empty in R?

Many people forget that functions like str_locate_all() require %>% unlist() or %>% . [[1]] . Then you can easily detect character(0) with the length() function if > 0 one can safely use the output of str_locate_all() for example.

How do I check if a column is empty in R?

You can check if a column is empty with the all() function. If all the values of a column are NA's or missing, then the all() function returns TRUE.


1 Answers

It seems that using length(vector_object) works:

vector.is.empty <- function(x) return(length(x) ==0 )

> v <- vector()
> class(v)
[1] "logical"
> length(v)
[1] 0
> vector.is.empty(v)
[1] TRUE
> 
> vector.is.empty(c())
[1] TRUE
> vector.is.empty(c(1)[-1])
[1] TRUE

Please tell if there is any case not covered.

like image 123
Yu Shen Avatar answered Oct 20 '22 20:10

Yu Shen