ifelse statement


I'm doing some ifelse statements, but I wonder how to include NA values. My statement is like:

df$x <- ifelse(df$y != df$z, 1, 0)

However if either y or z are equal to NA, the formula return NA rather then 1. I want it to still return 1 because y and z are not equal if one of them is NA.

So this is the output:
y z x
1 1 0
1 2 1

But I would like it like this:
y z x
1 1 0
1 2 1
2 NA 1

Do anyone have solution to this?

Regrads Marit

df$x <- ifelse(df$y != df$z | 
               , 1, 0)

Thank you for your answear!

Unfortunately, this does not work for me. The formula above was a simplification. I acutally have more and statement, so I can't have an or there.

This is the real formula:
df$x <- ifelse(df$t==df$u & df$y != df$z, 1, 0)

So if I put an or after df$y != df$z, I lose the first condition df$t==df$u which also need to be meet.


In R it can be useful to write your own functions and use them

equals_withna <- function(a,b)  {
  ifelse(test = a != b | (xor(is.na(a) , is.na(b)))
               , yes = 1, no = 0)}

df <- data.frame(t=c(0,1,2,3),
df$x <- pmax(equals_withna(df$t,df$u),equals_withna(df$y,df$z))


That solved my problem. Thank you a lot!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.