Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a list contains `NA`?

Tags:

r

na

When the right hand side is a vector, %in% can be used to check for NAs:

> NA %in% c(NA, 2)
[1] TRUE
> NA %in% c(1, 2)
[1] FALSE
> 1 %in% c(NA, 2)
[1] FALSE
> 1 %in% c(1, 2)
[1] TRUE

When the right hand side is a list, %in% behaves differently:

> NA %in% list(NA, 2)
[1] FALSE
> NA %in% list(1, 2)
[1] FALSE
> 1 %in% list(NA, 2)
[1] FALSE
> 1 %in% list(1, 2)
[1] TRUE

Is this a bug or a feature? Is this described in the documentation?

like image 949
jarauh Avatar asked Mar 05 '23 11:03

jarauh


2 Answers

We can use anyNA

anyNA(list(NA, 2))

if the list have vectors of length > 1, then use the recursive = TRUE

anyNA(list(c(1, 2), c(NA, 1)), recursive = TRUE)
#[1] TRUE
like image 75
akrun Avatar answered Mar 08 '23 00:03

akrun


To answer my second question: Yes, this phenomenon is described in the documentation (of course):

Factors, raw vectors and lists are converted to character vectors [...]

Thus, list(NA, 2) is coerced to c("NA", "2"). Obviously, NA is not in c("NA", "2"). Thus, anyNA should be used.

My personal take home message: Try to avoid %in% when the right hand side consists of lists.

like image 31
jarauh Avatar answered Mar 08 '23 01:03

jarauh