jarauh
jarauh

Reputation: 2006

How to check whether a list contains `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?

Upvotes: 4

Views: 6252

Answers (2)

jarauh
jarauh

Reputation: 2006

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.

Upvotes: 1

akrun
akrun

Reputation: 887991

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

Upvotes: 7

Related Questions