ToBeGeek
ToBeGeek

Reputation: 1143

How to see whether a vector is empty in R

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 ?

Upvotes: 26

Views: 47559

Answers (4)

jan-glx
jan-glx

Reputation: 9486

Unfortunately base R does not provide an is.empty function. You can implement one yourself:

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

Or use rlang::is_emtpy. But if(length(x)==0) will be understood just as well.

If for some unlikely reason you need to be sure that you are dealing with a "vector" you need to check that in addition with is.vector.

Upvotes: 1

R.Andres Castaneda
R.Andres Castaneda

Reputation: 770

The NULL case is not covered in the excellent example of @yu-shen. Sometimes it is not the same to have a NULL object and length-zero object. The function below cover those cases. Best,

is_empty <- function(x) {
  if (length(x) == 0 & !is.null(x)) {
    TRUE
  } else {
    FALSE
  }
}

x <- vector()
is_empty(x)
#> [1] TRUE

y <- NULL
length(y)
#> [1] 0
is_empty(y)
#> [1] FALSE

Created on 2022-08-26 with reprex v2.0.2

Upvotes: 4

Yu Shen
Yu Shen

Reputation: 2910

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.

Upvotes: 25

ialm
ialm

Reputation: 8717

From the help file of vector:

vector produces a vector of the given length and mode.
...

Usage

vector(mode = "logical", length = 0)

If you run the code, vec <- vector() and evaluate it, vec, returns logical(0). A logical vector of size 0. This makes sense, seeing as how the default arguments for the vector function is vector(mode="logical", length=0).

If you check length(vec), we know the length of our vector is also 0, meaning that our vector, vec, is empty.

If you want to create other types of vectors that are not of type logical, you can also read the help file of vector using ?vector. You will find that vector(mode='character') will make an empty character vector, vector(mode='integer') will make an empty integer vector, and so on.

You can also create empty vectors by calling the names of the other "atomic modes", as the help file calls them:

character(), integer(), numeric()/double(), complex(), character(), and raw().

Upvotes: 4

Related Questions