I am trying to extract rows of data with field "var" equals 0.
But I found "NA" were taken as 0:
There are 20 rows of 0 and 809 rows of "NA".
There are total 81291 rows in data frame d.
> length(d$var[d$var == "0"])
[1] 829
> length(d$var[d$var == 0])
[1] 829
The above 829 values include both 0 and "NA"
> length(d$var[d$var == "NA"])
[1] 809
> length(d$var[d$var == NA])
[1] 81291
Why does the above code gave the length of d?
x == NA
is not the way to test whether the value of some variablex
isNA
. Useis.na()
instead:Similarly, use
is.null()
to test whether an object is theNULL
object.