How to detect null values in a vector

22.9k views Asked by At

Whats the best way to detect null values in a vector?

If I have the vector below and want to know that the 4th position is null how would I do that?

vx <- c(1, 2, 3, NULL, 5)

is.null() returns only FALSE:

is.null(vx)
# [1] FALSE

and I'd like to get:

 FALSE FALSE FALSE TRUE FALSE
2

There are 2 answers

3
Pierre L On BEST ANSWER

As mentioned in the comments, NULL will not appear in length(vx). It is a special object in R for undefined values. From CRAN documentation:

NULL represents the null object in R: it is a reserved word. NULL is often returned by expressions and functions whose value is undefined.

But your question can still have learning opportunities with respect to lists. It will show up there. As in:

vlist <- list(1, 2, 3, NULL, 5)

Trying to identify the NULL value in a very large dataset can be tricky for novice R users. There are different techniques, but here is one that worked for me when I needed it.

!unlist(lapply(vlist, is.numeric))
[1] FALSE FALSE FALSE  TRUE FALSE

#or as user Kara Woo added. Much better than my convoluted code
sapply(vlist, is.null)
[1] FALSE FALSE FALSE  TRUE FALSE

#suggestion by @Roland
vapply(vlist, is.null, TRUE)
[1] FALSE FALSE FALSE  TRUE FALSE

If there are characters, then substitute in is.character or whatever class applies.

0
Joshua Cook On

Its possible that someone (like me) may come looking for is.null(), really needing is.na(). If so, remind yourself (as I did) that R has both a NULL and NA object. NULL signifies that there is no value whereas NA signifies that the value is unknown. If you are looking for missing values in a vector of values, what you're probably after is is.na().