Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect null values in a vector

Tags:

null

r

vector

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
like image 726
user3022875 Avatar asked Jun 08 '15 18:06

user3022875


People also ask

Can vector have NULL values?

A vector can't contain NULL .

What R function is used to test objects if they are null?

You can use the is. null function in R to test whether a data object is NULL.

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

The R function is. null indicates whether a data object is of the data type NULL (i.e. a missing value). The function returns TRUE in case of a NULL object and FALSE in case that the data object is not NULL.


1 Answers

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.

like image 128
Pierre L Avatar answered Oct 12 '22 09:10

Pierre L