jpf
jpf

Reputation: 65

Is %in% defined for NA valued vectors in R?

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)

Upvotes: 3

Views: 56

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

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))

Upvotes: 3

Related Questions