[R] Componentwise means of a list of matrices?

Marc Schwartz marc_schwartz at comcast.net
Tue Dec 30 16:16:20 CET 2008


on 12/30/2008 08:33 AM Stephan Kolassa wrote:
> Dear useRs,
> 
> I have a list, each entry of which is a matrix of constant dimensions.
> Is there a good way (i.e., not using a for loop) to apply a mean to each
> matrix entry *across list entries*?
> 
> Example:
> 
> foo <- list(rbind(c(1,2,3),c(4,5,6)),rbind(c(7,8,9),c(10,11,12)))
> some.sort.of.apply(foo,FUN=mean)
> 
> I'm looking for a componentwise mean across the two entries of foo,
> i.e., the following output:
> 
>      [,1] [,2] [,3]
> [1,]    4    5    6
> [2,]    7    8    9
> 
> [NB. My "real" application involves trimming and psych::winsor(), so
> anything that generalizes to this would be extra good.]
> 
> I've been looking at apply and {s,l,m,t}apply, by, with and aggregate
> and searched the list archives... any ideas?
> 
> Thanks a lot,
> Stephan


How about something like this:

> matrix(rowMeans(sapply(foo, c)), dim(foo[[1]]))
     [,1] [,2] [,3]
[1,]    4    5    6
[2,]    7    8    9


Essentially, first create matching elementwise rows:

> sapply(foo, c)
     [,1] [,2]
[1,]    1    7
[2,]    4   10
[3,]    2    8
[4,]    5   11
[5,]    3    9
[6,]    6   12


Then, get the row means:

> rowMeans(sapply(foo, c))
[1] 4 7 5 8 6 9


Then finally restructure the result to a matrix, using the dimensions of
foo[[1]].

This of course makes the assumption that each matrix is of the same size
and does not otherwise check for that.

HTH,

Marc Schwartz



More information about the R-help mailing list