When the right hand side is a vector, %in%
can be used to check for NA
s:
> 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?
We can use anyNA
anyNA(list(NA, 2))
if the list
have vector
s of length > 1, then use the recursive = TRUE
anyNA(list(c(1, 2), c(NA, 1)), recursive = TRUE)
#[1] TRUE
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With