Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an R function "parallel sum"? [duplicate]

Tags:

r

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

like image 655
Dan Lewer Avatar asked May 27 '20 12:05

Dan Lewer


2 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)))
like image 84
iamericfletcher Avatar answered Sep 30 '22 23:09

iamericfletcher


mapply is what you want:

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

# [1] 5 4 3 1 9
like image 29
Jrm_FRL Avatar answered Oct 01 '22 01:10

Jrm_FRL