48

假设您有矩阵列表。逐个元素基本计算平均矩阵的最方便方法是什么?假设我们有一个矩阵列表:

> A <- matrix(c(1:9), 3, 3) 
> A
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> B <- matrix(c(2:10), 3, 3) 
> B
     [,1] [,2] [,3]
[1,]    2    5    8
[2,]    3    6    9
[3,]    4    7   10
> my.list <- list(A, B)

所以期望的输出应该是:

     [,1] [,2] [,3]
[1,]  1.5  4.5  7.5
[2,]  2.5  5.5  8.5
[3,]  3.5  6.5  9.5
4

2 回答 2

74

您可以使用:

Reduce("+", my.list) / length(my.list)

根据评论,您希望两者都在矩阵列表meansd实现,而上述方法对于sd. 试试这个:

apply(simplify2array(my.list), 1:2, mean)
apply(simplify2array(my.list), 1:2, sd)
于 2013-10-07T06:49:25.277 回答
4

这是一个应该很快的替代方案,因为我们正在使用旨在处理矩阵的基本函数。我们只是获取您的列表并使用array将其转换为 3D 数组,然后使用apply或只是rowMeans...

#  Make some data, a list of 3 matrices of 4x4
ll <- replicate( 3 , matrix( sample(5,16,repl=TRUE) , 4 ) , simplify = FALSE )

#  Make a 3D array from list of matrices
arr <- array( unlist(ll) , c(4,4,3) )

#  Get mean of third dimension
apply( arr , 1:2 , mean )
#        [,1]     [,2]     [,3]     [,4]
#[1,] 3.000000 3.666667 3.000000 1.666667
#[2,] 2.666667 3.666667 3.333333 3.666667
#[3,] 4.666667 2.000000 1.666667 3.666667
#[4,] 1.333333 4.333333 3.666667 3.000000

或者您可以使用更快的rowMeans,指定您想要获得二维的平均值......

#  Get mean of third dimension
rowMeans( arr , dims = 2 )
#        [,1]     [,2]     [,3]     [,4]
#[1,] 3.000000 3.666667 3.000000 1.666667
#[2,] 2.666667 3.666667 3.333333 3.666667
#[3,] 4.666667 2.000000 1.666667 3.666667
#[4,] 1.333333 4.333333 3.666667 3.000000
于 2013-10-07T08:51:37.977 回答