1

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
Maël
  • 45,206
  • 3
  • 29
  • 67
max
  • 4,141
  • 5
  • 26
  • 55
  • This is to be expected since `NA_character_` is indeed *in* `c("apple", "bannana", NA_character_)` – Maël Sep 03 '22 at 19:48
  • 1
    `%in%` is defined as `match(x, table, nomatch = 0) > 0`. From `?match`: "For all types, `NA` matches `NA`". However, you can use the `incomparables` argument in `match`, `incomparables = NA`, to get your desired behaviour. – Henrik Sep 03 '22 at 20:29
  • 1
    Somewhat related: [NA matches NA, but is not equal to NA. Why?](https://stackoverflow.com/questions/25100974/na-matches-na-but-is-not-equal-to-na-why) – Henrik Sep 03 '22 at 20:40

1 Answers1

0

You can use any:

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

any("apple" == c("apple", "bannana", NA))
#[1] TRUE
Maël
  • 45,206
  • 3
  • 29
  • 67