[R] Componentwise means of a list of matrices?

hadley wickham h.wickham at gmail.com
Tue Dec 30 18:53:14 CET 2008


On Tue, Dec 30, 2008 at 10:21 AM, baptiste auguie <ba208 at exeter.ac.uk> wrote:
> I thought this was a good candidate for the plyr package, but it seems that
> l*ply functions are meant to operate only on separate list elements:
>
> Lists are the simplest type of input to deal with because they are already
> naturally
> divided into pieces: the elements of the list. For this reason, the l*ply
> functions don't
> need an argument that describes how to break up the data structure.
>
> (from: plyr: divide and conquer, Hadley Wickham 2008)
>
>  Perhaps a new case to consider?

Possibly, but here I would argue that the choice of data structure
isn't quite right - if the matrices all have the same dimension, then
they should be stored in an array, not a list:

foo <- list(rbind(c(1,2,3),c(4,5,6)),rbind(c(7,8,9),c(10,11,12)))
foo2 <- unlist(foo)
dim(foo2) <- c(dim(foo[[1]]), length(foo))

Then you can use apply (or aaply) directly on that matrix:

apply(foo2, c(1,2), mean)
apply(foo2, c(1,2), mean, trim = 0.1)

etc.

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list