[R] Componentwise means of a list of matrices?

baptiste auguie ba208 at exeter.ac.uk
Tue Dec 30 19:15:01 CET 2008


In fact, when writing my post I tried to do exactly what you did in  
creating a 3d array from the list, and I failed miserably! This is  
(imho) partly because the syntax is not very clean or straightforward  
as compared to the apply and *ply family. A list of matrices with  
equal dimensions is easily produced by mapply(... , simplify=F), or  
lapply, while an array needs to be created in a more verbose manner  
(as far as i know, some version of a loop).

I just remembered the abind package which makes this a bit easier,  
although the default is not quite as convenient for this purpose as  
I'd initially hoped:

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

library(abind)
foo3 <-  do.call(function(...) abind(..., along=3), foo)
foo2==foo3

Best wishes,

baptiste


On 30 Dec 2008, at 18:53, hadley wickham wrote:

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

_____________________________

Baptiste Auguié

School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK

Phone: +44 1392 264187

http://newton.ex.ac.uk/research/emag



More information about the R-help mailing list