Skip to content
Prev 301137 / 398503 Next

help with element-by-element sum with NA

On 2012-07-23 21:48, R. Michael Weylandt wrote:
I like Reduce(), but here are a couple more solutions:

1.
   tmp <- mapply(FUN = sum, A, B, C,
                 MoreArgs = list(na.rm = TRUE))
   matrix(tmp, nrow(A))

2.
Using the abind package to create a 3D array and
then using apply() to sum over the appropriate
columns in the array:

   require(abind)
   tmp <- abind(A, B, C, along = ncol(A) + 1)
   apply(tmp, 1:2, sum, na.rm = TRUE)

2a.
Both of the above solutions generate zeros where
one might prefer NA. Here's a way to get the NAs:

   sum2 <- function(x){
     ifelse(all(is.na(x)), NA, sum(x, na.rm = TRUE))
   }
   apply(tmp, 1:2, sum2)

Peter Ehlers