zugabe zugabe - 8 months ago 61
R Question

Mean matrix out of list of matrices

Is there a simple and nice answer to this question?

I have a given list "l" of matrices (with same ncol & nrow).


I want the mean of every cell.
I could do that with a for loop, but there should be a better solution!

With two matrices I could do it with (m1+m2)/2.
accepts only two parameters, so I cant do it like that:

do.call(.Primitive("+"),l) / length(l)

I'm looking forward for some nice answers :)

thanks in advance


Here are some alternatives:

1) Reduce

Reduce("+", l) / length(l)

2) simlify2array/apply A bit longer than (1); however, it does have the advadntage of readily extending to functions other than mean:

apply(simplify2array(l), 1:2, mean)

3) tapply Not as simple but like (2) it extends to functions other than mean:

array(tapply(unlist(l), sequence(sapply(l, length)), mean), dim(l[[1]]))

4) rowMeans

array(rowMeans(matrix(unlist(l), length(l[[1]]))), dim(l[[1]]))