Home > Back-end >  Is %in% defined for NA valued vectors in R?
Is %in% defined for NA valued vectors in R?

Time:08-09

The %in% -infix in R appears to work as expected with NA valued vector in either side of the expression (example below). I would like to ask if this behaviour is well-defined and are there major caveats using such expressions?

c(0, NA) %in% c(1, 2, 3, NA)

CodePudding user response:

If you look at the source code for %in% you will see it is implemented via match:

`%in%`
#> function (x, table) 
#> match(x, table, nomatch = 0L) > 0L

If you look at the docs for match you will see:

For all types, NA matches NA and no other value

So the answer to your question is "Yes, it is well defined, and documented". The caveats to its use is that NA values are sometimes uncaught and unexpected. If you want to match NA, a more conventional idiom would be is.na(x) or any(is.na(x))

  •  Tags:  
  • r na
  • Related