Is there an R function "parallel sum"?

Viewed 597

I would like to sum vectors that include NAs.

For example:

a <- c(5, 3, 1, NA, 2)
b <- c(NA, 1, 2, 1, 7)

The expected output would be:

[1] 5 4 3 1 9

sum doesn't work in this situation, as sum(a, b, na.rm = T) is equivalent to sum(c(a, b), na.rm = T).

+ does work (i.e. a + b) but does not remove the NAs.

You can use rowSums(cbind(a, b), na.rm = T), but in practice this can lead to messy code - for example if the vectors are columns of a data.table.

Is there an equivalent of pmax for sum, e.g. psum(a, b, na.rm = T)?

3 Answers

You can try the following using mapply to apply the sum function to the two vectors a and b. The na.rm=TRUE instructs to remove NA values from the calculation:

a <- c(5, 3, 1, NA, 2)
b <- c(NA, 1, 2, 1, 7)

mapply(sum, a, b, na.rm=TRUE)

Output:

[1] 5 4 3 1 9

Or, you can opt to use reduce as suggested by @Roland :

Reduce("+", lapply(list(a,b), function(x) replace(x, is.na(x), 0)))

mapply is what you want:

mapply(sum, a, b, na.rm = TRUE)

# [1] 5 4 3 1 9

you can make your own psum function

psum <- function(x,y){
x[is.na(x)] <- 0
y[is.na(y)] <- 0
x+y
}


> psum(a,b)
[1] 5 4 3 1 9
Related