mercredi 4 novembre 2015

R Ifelse statement not working due to NAs

Here is a problem that I am facing when using ifelse function in the presence of NAs.

Data:

x=data.frame(rbind(c(1,1,0),c(0,NA,1)))
colnames(x)=c("a","b","c")

objective: create a column "test", that changes to 0, if either a or b is 1. if neither a or b is 1, test=c

problem: when b=NA, which is not equal to 1, test=NA, #when it should be 1.

works correctly for row 1 but not for row 2.

x=mutate(x,
         test=ifelse((a==1|b==1),0,c))

> x
  a  b c test
1 1  1 0    0
2 0 NA 1   NA

Any sugguestions on how to fix it?

Aucun commentaire:

Enregistrer un commentaire