Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise mean over list of matrices [duplicate]

Tags:

r

Suppose you have list of matrices. What is the most convenient way to calculate the mean matrix on an element by element basic? Suppose we have a list of matrices:

> 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)

So the desired output should be:

     [,1] [,2] [,3]
[1,]  1.5  4.5  7.5
[2,]  2.5  5.5  8.5
[3,]  3.5  6.5  9.5
like image 481
Andrej Avatar asked Oct 07 '13 06:10

Andrej


2 Answers

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)
like image 78
cogitovita Avatar answered Nov 13 '22 05:11

cogitovita


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
like image 27
Simon O'Hanlon Avatar answered Nov 13 '22 05:11

Simon O'Hanlon