列表中矩阵的逐元素平均值

51

假设你有一组矩阵。如何以逐元素的方式计算平均矩阵? 假设我们有一组矩阵:

> 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

2
你能透露一点你想做什么的线索吗?在这种情况下,(A + B)/2可以得到你的答案,但我猜你正在寻找其他东西... - A5C1D2H2I1M1N2O1R2T1
是的,你说得对。我需要应用 mean()sd() - Andrej
4
因为这篇帖子的标题与重复回答相比非常具有描述性,所以被点赞了。 - Megatron
2个回答

79

你可以使用:

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

根据评论,您希望在矩阵列表上实现meansd,但是以上方法对于sd不会很顺利。请尝试使用以下方法:

apply(simplify2array(my.list), 1:2, mean)
apply(simplify2array(my.list), 1:2, sd)

在我的基准测试中,simplify2array 方法比 Reduce 慢了近1000倍(因为它调用了 mean 函数 nrow*ncol 次):https://dev59.com/OXbZa4cB1Zd3GeqPElnM#73248994。 - nisetama
这里提供的simplify2array方法的另一个用例是,如果合适的话,您可以在其末尾添加"na.rm=TRUE"。虽然根据@nisetama的基准测试,Reduce是更有效的方法,但在需要时它将无法工作。 - ChrisWResearch

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,它更快,并指定要在2个维度上获取平均值...

#  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

适用于行均值,但不适用于行中位数... - David

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接