Element-wise mean over list of matrices [duplicate]

Solution 1:

You can use:

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

According to comments, you want both mean and sd implemented on a list of matrices, and the above ways will not work smoothly for sd. Try this instead :

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

Solution 2:

Here is an alternative that should be pretty quick as we are working with base functions designed to work with matrices. We just take your list and use array to turn it into a 3D array then either use apply or just 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

Or you can use rowMeans which is quicker, specifying you want to get the mean over 2 dimensions...

#  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