looking for R function that utilizes ifelse when there are NA

Viewed 37

I have this data in which I require an output as shown.

  • If a is 0 and b is 0 , then c is assigned value 0
  • If a is 0 and b is 1 , then c is assigned value 1
  • If a is 0 and b is NA , then c is assigned value 0
  • If a is 1 and b is NA , then c is assigned value 1
    a<-c(0,0,0,1,1,1,0,1)
    b<-c(1,0,0,0,1,0,NA,NA)
    data<-data.frame(a,b)
    
    data$c<-c(1,0,0,1,1,1,0,1)
2 Answers

Either of these will work in instant case

pmax(a, b, na.rm = T)
[1] 1 0 0 1 1 1 0 1

data$c <- +(as.logical(rowSums(data, na.rm = T)))

 data$c
[1] 1 0 0 1 1 1 0 1

dplyr::if_else has a last argument to provide an additional value, if condition provided results in NA

Maybe this:

apply(data, 1, max, na.rm=T)
1 0 0 1 1 1 0 1
Related