lundi 4 mars 2019

ifelse with NAs not always evaluating as NA?

While NAs and ifelse have been discussed here before, I would like to understand a particular detail of this question, which has not yet been addressed before.

A reproducible example:

transflag <- c("YES", "YES", "NO", "NO", "NO", "NO", "YES", "YES", "NO")
class <- c("SC", "IC", "IC", "SC", NA, "IC", "IC", NA, NA)
prod <- c("P1", "P2", NA, "P1", "P2", "P1", NA, "P2", "P1")

data <- data.frame(class, prod, transflag)

data$transflag <- as.character(data$transflag )
data$class <- as.character(data$class )
data$prod <- as.character(data$prod )

data$transflag4 <- ifelse(data$prod == "P1" & data$class == "SC" , "NO", data$transflag)

data$transflag5 <- ifelse(data$prod == "P2" & data$class == "SC" , "NO", data$transflag)

How come that in transflag4 , the result is NA, while there is a result in transflag5 is defined? This is strange, considering that other posters mentioned that the evaluation of anything with NA is NA (recode variables with NAs with ifelse() in R)

Aucun commentaire:

Enregistrer un commentaire