Maximilian
Maximilian

Reputation: 4229

Why is the second ifelse not evaluated?

In the code below, I do not understand why the second ifelse() is not evaluated. Can someone explain it? How to rewrite the ifelse statement?

The y1==1 and y2==1 in the last row are matched, and the column result should be filled with 1.

df <- data.frame(x1=c(0,0,NA,NA,NA),y1=c(NA,NA,NA,NA,1),x2=c(0,NA,NA,0,NA),
                 y2=c(1,NA,NA,NA,1))

df$result <- with(df, ifelse((x1==0 & x2==0), 0, ifelse((y1==1 & y2==1), 1, 100)))

Upvotes: 2

Views: 91

Answers (3)

R. Schifini
R. Schifini

Reputation: 9313

Try this:

df$result <- with(df, ifelse((x1==0 & x2==0) & !is.na(x1==0 & x2==0), 0,
                             ifelse((y1==1 & y2==1), 1, 100)))

Result:

> df
  x1 y1 x2 y2 result
1  0 NA  0  1      0
2  0 NA NA NA     NA
3 NA NA NA NA     NA
4 NA NA  0 NA     NA
5 NA  1 NA  1      1

Solution using apply() and if()

If you want to use if() and apply() instead of ifelse() do:

df$result = apply(df,1,function(x){

    if(is.na(x["x1"]==0 & x["x2"]==0) & is.na(x["y1"]==1 & x["y2"]==1)){
        return(NA)
    }

    if(!is.na(x["x1"]==0 & x["x2"]==0) & (x["x1"]==0 & x["x2"]==0)){
        return(0)
    }else if(!is.na(x["y1"]==1 & x["y2"]==1) & (x["y1"]==1 & x["y2"]==1)){
        return(1)
    }else{
        return(100)
    }

})

The result is the same as above.

Upvotes: 3

akrun
akrun

Reputation: 886948

We can try with pmax and rowSums

df$result <- pmax(+(!!rowSums(df[c(TRUE, FALSE)])), 
          +(!!rowSums(df[c(FALSE, TRUE)])), na.rm = TRUE)
df$result
#[1]  0 NA NA NA  1

Upvotes: 2

dimitris_ps
dimitris_ps

Reputation: 5951

It cannot evaluate NAs. Notice that (x1==0 & x2==0) is TRUE, NA, NA, NA So ifelse( (df$x1==0 & df$x2==0), 0, "Something) is 0, NA, NA, NA

I would suggest the following

library(dplyr)
df$result <- case_when(df$x1==0 & df$x2==0 & !is.na(df$x1) & !is.na(df$x2) ~ 0,
                   df$y1==1 & df$y2==1 ~ 1,
                   TRUE ~ 100))

Upvotes: 1

Related Questions