1

I want to calculate A+B in r

A <- c(NA,2,3,4,5)
B <- c(1,2,3,4,NA)

The ideal output is:

(1,4,6,8,5)

Is there a way to achieve this without replacing NA with 0? Thanks.

Jeremy
  • 849
  • 6
  • 15
  • 2
    https://stackoverflow.com/questions/13123638/there-is-pmin-and-pmax-each-taking-na-rm-why-no-psum – rawr Mar 09 '20 at 15:36
  • 2
    Out of curiosity, what would be your expected output for A*B and A/B? – asachet Mar 09 '20 at 15:36
  • Sorry, I made a bad example here. I just wanted to say that I need to get the mean or sum or some other analysis out of many datasets, so replacing the NA with 0 may introduce bias at some time. – Jeremy Mar 09 '20 at 15:44

2 Answers2

2

you can do it with rowSums:

rowSums(data.frame(A,B), na.rm=TRUE)
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
2

You can always implement your own sum:

mysum <- function(...) {
  plus <- function(x, y) {
    ifelse(is.na(x), 0, x) + ifelse(is.na(y), 0, y)
  }
  Reduce(plus, list(...))
}

A <- c(NA,2,3,4,5)
B <- c(1,2,3,4,NA)

mysum(A, B)
#> [1] 1 4 6 8 5
mysum(A, A)
#> [1]  0  4  6  8 10
mysum(A, B, A, B)
#> [1]  2  8 12 16 10

Created on 2020-03-09 by the reprex package (v0.3.0)

asachet
  • 6,620
  • 2
  • 30
  • 74