Sum a list of matrices [duplicate]

Solution 1:

Use Reduce.

## dummy data

.list <- list(matrix(1:25, ncol = 5), matrix(1:25, ncol = 5))

Reduce('+', .list)
##       [,1] [,2] [,3] [,4] [,5]
## [1,]    2   12   22   32   42
## [2,]    4   14   24   34   44
## [3,]    6   16   26   36   46
## [4,]    8   18   28   38   48
## [5,]   10   20   30   40   50

Solution 2:

I think @mnel's answer is the more efficient but this is another approach:

apply(simplify2array(.list), c(1,2), sum)

    [,1] [,2] [,3] [,4] [,5]
[1,]    2   12   22   32   42
[2,]    4   14   24   34   44
[3,]    6   16   26   36   46
[4,]    8   18   28   38   48
[5,]   10   20   30   40   50

Solution 3:

You could you do.call with some monkeying around but it loses its eloquence:

.list <- list(matrix(1:25, ncol=5), matrix(1:25,ncol=5), matrix(1:25,ncol=5))

x <- .list[[1]]
lapply(seq_along(.list)[-1], function(i){
    x <<- do.call("+", list(x, .list[[i]]))
})
x