How to detect null values in a vector

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.


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().

Tags:

Null

R

Vector