Python Newbie
Python Newbie

Reputation: 277

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?

Upvotes: 2

Views: 1462

Answers (1)

AntoniosK
AntoniosK

Reputation: 16121

As the conditions only care about the presence of 1 in a and b, I'd suggest to create a process that replaces NAs with a value that is not 1.

Something like

library(plyr)

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

# create an updated version of x where NAs are replaced with 0s
x2 = sapply(x, function(i){ifelse(is.na(i),0,i)})

x2 = data.frame(x2)

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

# update initial dataset
x$test = x2$test

x

#   a  b c test
# 1 1  1 0    0
# 2 0 NA 1    1

If you prefer to create a ifelse condition try this

mutate(x, test = ifelse((a!=1 | is.na(a)) & (b!=1 | is.na(b)), c, 0))

Upvotes: 2

Related Questions