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:
df_noNA <- data.frame(a = c(1, 1, 2, 2, 2 ,2),
b = c(2, 2, 1, 1, 2, 2),
c = c(rep(2, 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" "c==1" "c==1"
However, I was wondering if there was a more direct way to tell ifelse
to ignore NAs?
EDIT: I am looking for an efficient solution to this problem.
As noted in the comments by @Cath, I can tell ´ifelse´ to ignore NAs:
ifelse(df$a==1 & !is.na(df$a), "a==1",
ifelse(df$b==1 & !is.na(df$b), "b==1",
ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))
However, as also noted by @akrun, it seems somewhat lengthy to type !is.na(x_i)
for every column (personally it also seems redundant to me to specify that x should equal 1 and not be NA). At this moment, the workaround of first replacing NAs with a value that is not present in the data set (e.g., 2 in this case) and then writing an ´ifelse´ statement without !is.na(x_i)
seems more efficient.