stkubr stkubr - 11 months ago 55
R Question

NA == 1 check returns NA

Could someone explain me why:

NA == 1 #NA #expect FALSE
NA == NA #NA #expect TRUE
1 == NA #NA #expect FALSE
NA == TRUE #NA #expect FALSE

A live example of the usage is
df[df$SomeAttribute == 1,]
where some of

I know one can use
which(df$SomeAttribute == 1)
just question the sanity of logic operations on


The NA simply means that a value is missing/unknown. Therefore NA == 1 yields NA. The outcome of the comparison with == is unknown, since we don't know if the missing value is 1 or something else.

The same reasoning can be applied to the other tests, which is why they all return NA.

As pointed out by @akrun in a comment, the proper way to check whether a value x is missing is to use the function A comparison of the type x == NA would not give the desired result.