Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

combining two variables together, including NA

I am trying to combine two binary variables together as a single variable, so if there is a 0 in one and a 1 in the other it would be a 1. This contains NAs. Example

a <- c("A", NA, 0)
b <- c("B",0,  1)
c <- c("C", 0, 0)
d <- c("D", 0, 1)
e <- c("E", NA, NA)
aa<- rbind(a,b,c,d,e)
aa <- as.data.frame(aa) 

I would like to code this to give me:

a <- c("A", NA, 0, 0)
b <- c("B",0,  1, 1)
c <- c("C", 0, 0, 0)
d <- c("D", 0, 1, 1)
e <- c("E", NA, NA, NA)
bb<- rbind(a,b,c,d, e)
bb <- as.data.frame(bb) 

I think this is an easy fix.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use base R, use rowSums to create the V4 column by comparing the columns of interest with 1 and then replace the values in ‘V4’ to NA where there are all NAs in a row in columns 2 and 3

aa$V4 <- rowSums(aa[-1] == 1,  na.rm = TRUE)
aa$V4[rowSums(is.na(aa[2:3])) == 2] <- NA

-output

> aa
  V1   V2   V3 V4
a  A <NA>    0  0
b  B    0    1  1
c  C    0    0  0
d  D    0    1  1
e  E <NA> <NA> NA
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading