How to find if a list contains a null value in R?

Viewed 1282

%in% does not work as logically expected:

> 1 %in% list(1,NULL,3)
[1] TRUE
> NULL %in% list(1,NULL,3)
logical(0)

How can I get a TRUE response if a list contains a NULL element?

4 Answers

You can also wrap your NULL in a list() and it seems to work

> list(NULL) %in% list(1,3)
[1] FALSE

> list(NULL) %in% list(1,NULL,3)
[1] TRUE

> list(NULL) %in% list(Inf,-Inf,numeric(0),NA, NaN)
[1] FALSE

You can use is.null in sapply:

any(sapply(list(1,NULL,3), is.null))
#[1] TRUE

you can lapply/sapply the list to check where the length is = 0

> sapply( list(1,NULL,3), function(x) length(x) == 0 )
[1] FALSE  TRUE FALSE

You then can wrap that in any()

Base R using Map:

any(unlist(Map(is.null, lst)))

Base R using mapply:

any(mapply(is.null, lst, SIMPLIFY = TRUE))

Data:

lst <- list(1,NULL,3)
Related