Merge two columns maintaning missing values

  • A+
Category:Languages

I am trying to add two columns. My dataframe is like this one:

data <- data.frame(a = c(0,1,NA,0,NA,NA),                    x = c(NA,NA,NA,NA,1,0),                    t = c(NA,2,NA,NA,2,0)) 

I want to add some of the columns like this:

yep  <- cbind.data.frame( data$a, data$x, rowSums(data[,c(1, 2)], na.rm = TRUE)) 

However the output looks like this:

> yep        data$a  data$x   rowSums(data[,c(1, 2)], na.rm = TRUE)   1        0      NA                                      0   2        1      NA                                      1   3       NA      NA                                      0   4        0      NA                                      0   5       NA       1                                      1   6       NA       0                                      0 

And I would like an oputput like this:

> yep        data$a  data$x   rowSums(data[,c(1, 2)], na.rm = TRUE)   1        0      NA                                      0   2        1      NA                                      1   3       NA      NA                                      NA   4        0      NA                                      0   5       NA       1                                      1   6       NA       0                                      0 

If the columns contain only NA values I want to leave the NA values.

How I could achive this?

 


Base R (ifelse):

cbind(data$a,data$x,ifelse(is.na(data$a) & is.na(data$x),NA,rowSums(data[,1:2],na.rm = TRUE))) 

If you are looking for the column name then replace cbind with cbind.data.frame

Output:

      [,1] [,2] [,3] [1,]    0   NA    0 [2,]    1   NA    1 [3,]   NA   NA   NA [4,]    0   NA    0 [5,]   NA    1    1 [6,]   NA    0    0 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: