Reputation: 477
When I compare a number to NA
in R using ==
this yields NA
> 1==NA
[1] NA
However, if I use %in%
> 1 %in% c(NA)
[1] FALSE
What's going on here? Isn't %in%
using ==
behind the scenes?
Upvotes: 1
Views: 84
Reputation: 10350
Concerning the comparison operator ==
, it handles NA
as follows:
Missing values (NA) and NaN values are regarded as non-comparable even to themselves, so comparisons involving them will always result in NA. Missing values can also result when character strings are compared and one is not valid in the current collation locale. (see
?`==`
)
And from ?`%in%`
we learn:
Exactly what matches what is to some extent a matter of definition. For all types, NA matches NA and no other value. For real and complex values, NaN values are regarded as matching any other NaN value, but not matching NA.
That %in% never returns NA makes it particularly useful in if conditions.
This happens since (as @akrun also pointed out in the comment)
%in%
is currently defined as"%in%" <- function(x, table) match(x, table, nomatch = 0) > 0
Upvotes: 4