list 对矩阵列表求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11641701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum a list of matrices
提问by Seen
I have a list where each element is a 5*5 matrix. Eg
我有一个列表,其中每个元素都是一个 5*5 矩阵。例如
[[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 an apply-like function to sum matrix [1] to [n], and return a 5*5 matrix as a result (each element is a sum of the corresponding elements in each of the matrix in the list) ?
如何使用类似应用的函数将矩阵 [1] 与 [n] 相加,并返回一个 5*5 矩阵作为结果(每个元素是列表中每个矩阵中相应元素的总和)?
回答by mnel
Use Reduce
.
使用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
回答by Jilber Urbina
I think @mnel's answer is the more efficient but this is another approach:
我认为@mnel 的答案更有效,但这是另一种方法:
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
回答by Tyler Rinker
You could you do.call
with some monkeying around but it loses its eloquence:
你可以do.call
胡说八道,但它失去了口才:
.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