Summarize Matrix List

I have a list where each element is a 5 * 5 matrix. For example,

[[1]] V1 V2 V3 V4 V5 [1,] 0.000000 46.973700 21.453500 338.547000 10.401600 [2,] 43.020500 0.000000 130.652000 840.526000 56.363700 [3,] 12.605600 173.238000 0.000000 642.075000 19.628100 [4,] 217.946000 626.368000 481.329000 0.000000 642.341000 [5,] 217.946000 626.368000 481.329000 0.000000 642.341000 [[2]] V1 V2 V3 V4 V5 [1,] 0.000000 47.973700 21.453500 338.547000 10.401600 [2,] 143.020500 0.000000 130.652000 840.526000 56.363700 [3,] 312.605600 17.238000 0.000000 642.075000 19.628100 [4,] 17.946000 126.368000 481.329000 0.000000 642.341000 [5,] 217.946000 626.368000 481.329000 0.000000 642.341000 ... 

How can I use the application function to sum the matrix [1] - [n] and return the 5 * 5 matrix as a result (each element is the sum of the corresponding elements in each matrix in the list)?

+48
list matrix r
Jul 25 2018-12-12T00:
source share
4 answers

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 
+84
Jul 25 '12 at 2:20
source share

I think @mnel's answer is more efficient, but this is a different 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 
+11
Jul 25 '12 at 16:11
source share

You could do.call with some monkeys, but lose your 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 
+3
Jul 25 2018-12-12T00:
source share

there is an even simpler way:

 matlist <- list(matrix(1:25, ncol=5), matrix(1:25,ncol=5)) combmat <- matlist[[1]]+matlist[[2]] > combmat [,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 

although I think using Reduce is the best way to go.

-one
Jul 25 '12 at 7:27
source share



All Articles