Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two columns maintaning missing values

Tags:

merge

r

rowsum

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?

like image 555
Eric González Avatar asked Dec 23 '22 03:12

Eric González


1 Answers

Base R:

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)
)

yep <- cbind.data.frame( data$a, data$x, rs = rowSums(data[,c(1, 2)], na.rm = TRUE))
yep$rs[is.na(data$a) & is.na(data$x)] <- NA
yep
like image 161
r.user.05apr Avatar answered Jan 04 '23 23:01

r.user.05apr