Jeremy
Jeremy

Reputation: 876

A + B with NA in r

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.

Upvotes: 1

Views: 125

Answers (2)

asachet
asachet

Reputation: 6921

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)

Upvotes: 2

you can do it with rowSums:

rowSums(data.frame(A,B), na.rm=TRUE)

Upvotes: 2

Related Questions