总结一个matrix列表
我有一个列表,其中每个元素是一个5 * 5的matrix。 例如
[[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 ...
我怎样才能使用一个类似apply的函数来求和matrix[1]到[n],然后返回一个5 * 5的matrix(每个元素是列表中每个matrix的相应元素的总和)?
使用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
我认为@ 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
你可以做一些可怕的事情,但它失去了它的口才:
.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
甚至有一个更简单的方法:
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
尽pipe我认为使用Reduce是最好的select。