mercredi 7 juin 2017

understanding ifelse with NAs [duplicate]

This question already has an answer here:

I can nest multiple ifelse statements as follows:

ifelse(2==1, "2==1", ifelse(3==1, "3==1", ifelse(1==1, "1==1", NA)))
#[1] "1==1"

However, it seems as if NAs are getting into the way. The following returns ...

df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))
ifelse(df$a==1, "a==1", ifelse(df$b==1, "b==1", ifelse(df$c==1, "c==1", NA)))
#[1] "a==1" "a==1" NA     NA     NA     NA    

... instead of the desired

#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1" 

I could first assign different values to NAs to obtain the desired result (only replacing some of the NAs here for demonstration):

df_noNA <- data.frame(a = c(1, 1, 2, 2, 2 ,2),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))

ifelse(df_noNA$a==1, "a==1", ifelse(df_noNA$b==1, "b==1", ifelse(df_noNA$c==1, "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1" NA     NA   

However, I was wondering if there was a more direct way to tell ifelse to ignore NAs?

Aucun commentaire:

Enregistrer un commentaire