0

I have a data frame called data. I have a column called ColB with all NA values and a column called ColC with all integer values and no NAs.

When I use the subset syntax I get some false results (all NAs):

nrow(data[data$ColB == "XXXX",])

But when I run the same syntax using the which function I get no results, as I would expect and want.

data[which(data$ColB== "XXXX"),]

Also, when I run the following:

{data[data$ColC == 185,]}

I get the correct result/output which is one matching row.

Why is this? Is this something about having NA in the data? And is subsetting by column reference (instead of using subset function) without using which not recommended?

0

1 Answer 1

1

NA is a logical constant of length 1 which contains a missing value indicator.

And e.g. which( c( NA,NA,NA) ) returns a zero length integer vector as none of the comparisons can be considered TRUE, the same as if you tried which( c(FALSE,FALSE,FALSE) ). Therefore you are trying to subset your data.frame with nothing, returning nothing.

If you need to do comparisons using data with NA values, use the is.na(), function, e.g. consider:

x <- c( NA , is.na(NA) , NA )
which( x )
#[1] 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.