[R] get means of elements of 5 matrices in a list
Peter Ehlers
ehlers at ucalgary.ca
Tue Apr 27 18:03:42 CEST 2010
On 2010-04-27 9:05, David Freedman wrote:
>
> I've got a list of 5 matrices that are each 5 x 6. I'd like to end up with a
> 5 x 6 matrix that contains the mean value of the 5 original matrices. I can
> do this by brute force, but there must be a better way than making each
> matrix into a vector and then remaking a matrix
>
> thanks very much for any help
> david freedman
>
> ll=list(structure(c(9.7, 17.6, 20.8, 24.1, 33.8, 14.5, 25.7, 29.8,
> 33.6, 44.8, 21.8, 32.6, 37.5, 40.9, 53.3, 16.7, 26.1, 29.5, 32.7,
> 42.6, 26.2, 34.3, 37, 39.8, 47.1, 31.9, 40.3, 43.3, 46.2, 54.1
> ), .Dim = 5:6), structure(c(9.4, 17.7, 20.7, 24.1, 33.7, 14.5,
> 25.7, 29.8, 33.6, 44.8, 21.8, 32.7, 37.5, 40.9, 53.1, 16, 26,
> 29.5, 32.7, 42.7, 25.6, 34.1, 37, 39.8, 47.1, 31.9, 40.3, 43.3,
> 46.1, 54.1), .Dim = 5:6), structure(c(9.6, 17.7, 20.8, 24.4,
> 34.3, 14.5, 25.7, 29.8, 33.6, 44.8, 21.8, 32.6, 37.5, 40.9, 53.2,
> 16.7, 26.1, 29.5, 32.8, 42.8, 26.2, 34.2, 36.8, 39.9, 47.1, 31.9,
> 40.3, 43.3, 46.1, 54.8), .Dim = 5:6), structure(c(9.7, 17.6,
> 20.7, 24.1, 33.8, 14.5, 25.7, 29.8, 33.6, 44.8, 21.8, 32.6, 37.5,
> 41.1, 52.6, 16.7, 26.1, 29.5, 32.8, 42.8, 26.1, 34.3, 37, 40,
> 47.1, 31.9, 40.3, 43.3, 46.2, 54.9), .Dim = 5:6), structure(c(8.6,
> 17.6, 20.7, 24.1, 33.8, 14.5, 25.6, 29.8, 33.6, 44.8, 21.8, 32.6,
> 37.5, 40.9, 52.5, 16, 26, 29.4, 32.8, 42.8, 25.6, 34.2, 37, 40.1,
> 47.1, 31.9, 40.3, 43.1, 46.1, 54.1), .Dim = 5:6))
>
> ll
> x=rbind(as.vector(ll[[1]]),as.vector(ll[[2]]),as.vector(ll[[3]]),as.vector(ll[[4]]),as.vector(ll[[5]]));
> x
> x2=apply(x,2,mean); matrix(x2,byrow=F,nrow=5);
>
Here is one more way: create a 3-dim array, then apply mean():
za <- array(unlist(ll), dim = c(5,6,5))
mn <- apply(za, c(1,2), mean)
--
Peter Ehlers
University of Calgary
More information about the R-help
mailing list