1) abind This works even if the constituent matrices are not single-row matrices. abind creates a 3-dimensional array from the L sublists, and then sum is applied along parallel elements using na.rm = TRUE .
library(abind) L <- lst[as.character(agg.nam)] apply(abind(L, along = 3), 1:2, sum, na.rm = TRUE)
In the case of the input of the question, we get the following output matrix:
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 3 6 0 2 1
2) an array . It also works and does not use any packages. It works the same way, except that it converts L to a 3D array using array . L on top.
make3d <- function(List) array(unlist(List), c(dim(List[[1]]), length(List))) apply(make3d(L), 1:2, sum, na.rm = TRUE)
3) mapply Using mapply defines a parallel sum that removes the NA and then applies it using Reduce . Packages are not used. L - from (1).
psum <- function(x, y) array(mapply(sum, x, y, MoreArgs = list(na.rm = TRUE)), dim(x)) Reduce(psum, L)
3a) . Option (3):
sumNA <- function(...) sum(..., na.rm = TRUE) array(do.call(mapply, c(sumNA, L)), dim(L[[1]]))