Is there a way to have conditional subscripts if the conditional vector contains NAs? Assume i have a 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 was not for the NA in dframe$d this would be straight forward. I have seen %in%
syntax like here to get around NAs, but do not know how to manage it for conditions.
I can see that this is somewhat of a general problem, since I am not quite sure whether I want to obtain an NA for the missing value in the condition or something else.
But I am also interested to learn how people handle this situation.
In my specific situation in would simply be helpful when NA was treated like FALSE in the condition.
You can just restrict your indexing to the non NA values
dframe[ dframe$d > 9 & !is.na(dframe$d), "a"] <- NA
Edit: Here is a more compact alternative from the R Inferno:
dframe[ which(dframe$d > 9), "a"] <- NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With