[R] Element by element mean of a list of matrices

Peter Langfelder peter.langfelder at gmail.com
Tue Mar 15 21:41:27 CET 2011


On Tue, Mar 15, 2011 at 1:17 PM, hihi <v.p.mail at freemail.hu> wrote:
> Hi All,
> is there any effiective and dense/compact method to calculate the mean of a list of - of course coincident - matrices on an element by element basis? The resulting matrix' [i, j]-th element is the mean of the list's matrices' [i, j]-th elements respectively...
> Iterating by for statement is quite straightforward, but I am seeking for a more elegant solution, and my attempt with the apply family of functions did not work.

Hi,

in the package WGCNA (I'm the maintainer) we have functions pmean,
pmedian, pquantile etc. if you have your list of matrices in the
variable matList, you should be able to do something like

do.call(pmean, matList)

Example:


library(WGCNA)
a = matrix(c(1:9), 3, 3);
b = a + sample(c(-1, 1), 9, replace = TRUE);
matList = list(a=a, b=b);
do.call(pmean, matList)

results:

> a
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> b
     [,1] [,2] [,3]
[1,]    0    5    8
[2,]    1    4    9
[3,]    4    7   10
> do.call(pmean, matList)
     [,1] [,2] [,3]
[1,]  0.5  4.5  7.5
[2,]  1.5  4.5  8.5
[3,]  3.5  6.5  9.5


HTH,

Peter



More information about the R-help mailing list