Unexpected behavior with using %in% with NA

Viewed 34

When testing if a string is in another vector, I have been using %in% like this:

> "apple" %in% c("apple", "bannana")
[1] TRUE
> "carrot" %in% c("apple", "bannana")
[1] FALSE

However, when I input NA, it returns TRUE if there's another NA in the vector. I would have expected it to return NA. Is there another function I can use to get around this behavior?

> NA_character_ %in% c("apple", "bannana", NA_character_)
[1] TRUE
1 Answers

You can use any:

any(NA_character_ == c("apple", "bannana", NA_character_))
#[1] NA

any("apple" == c("apple", "bannana", NA))
#[1] TRUE
Related