How to handle conditional data.frame indexes containing NA?

Is there a way to have conditional indices if the conditional vector contains NA? Suppose I have data.frame, like this

dframe <- data.frame(a=c(1,32,4,5,8),b=c(1,2,3,4,5),d=c(NA,5,5,10,9)) dframe[dframe$d > 9,"a"] <- NA 

If it weren't for NA in dframe $ d, that would be straightforward. I saw the %in% syntax, for example here , to get around the HC, but I donโ€™t know how to manage it for conditions. I see that this is some kind of general problem, since I'm not quite sure if I want to get NA for the missing value in the state or something else. But Iโ€™m also interested to know how people deal with this situation.

In my particular situation, it would simply be useful when the NA was considered to be FALSE in state.

+4
source share
2 answers

You can simply restrict indexing to non NA values

 dframe[dframe$d > 9 & !is.na(dframe$d),"a"] <- NA 
+5
source

You were close. You had a condition and %in% . Just not a link. This is actually straightforward. Just use %in% with TRUE , it will return all other values, where as NA will be replaced with FALSE

  dframe[(dframe$d > 9) %in% TRUE, "a"] <- NA 
+5
source

All Articles