假设你有矩阵列表。按元素基本计算元素上的平均矩阵的最方便方法是什么?假设我们有一个矩阵列表:
> 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
您可以使用:
Reduce("+", my.list) / length(my.list)
根据评论,您希望在矩阵列表中实现mean
和sd
,并且上述方法对于sd
来说不会顺利进行。试试这个:
apply(simplify2array(my.list), 1:2, mean)
apply(simplify2array(my.list), 1:2, sd)
这是一个应该非常快的替代方案,因为我们正在处理旨在处理矩阵的基本函数。我们只是拿你的列表并使用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