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:
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With