# [R] get means of elements of 5 matrices in a list

Marc Schwartz marc_schwartz at me.com
Tue Apr 27 17:41:06 CEST 2010

```On Apr 27, 2010, at 10:19 AM, Marc Schwartz wrote:

> On Apr 27, 2010, at 10:05 AM, 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);
>
>
>
>> matrix(rowMeans(sapply(ll, unlist)), nrow = length(ll))
>      [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
> [1,]  9.40 14.50 21.80 16.42 25.94 31.90
> [2,] 17.64 25.68 32.62 26.06 34.22 40.30
> [3,] 20.74 29.80 37.50 29.48 36.96 43.26
> [4,] 24.16 33.60 40.94 32.76 39.92 46.14
> [5,] 33.88 44.80 52.94 42.74 47.10 54.40

In the interest of correctness, unlist() is not really needed here and as.vector() should be used instead:

> matrix(rowMeans(sapply(ll, as.vector)), nrow = length(ll))
[,1]  [,2]  [,3]  [,4]  [,5]  [,6]
[1,]  9.40 14.50 21.80 16.42 25.94 31.90
[2,] 17.64 25.68 32.62 26.06 34.22 40.30
[3,] 20.74 29.80 37.50 29.48 36.96 43.26
[4,] 24.16 33.60 40.94 32.76 39.92 46.14
[5,] 33.88 44.80 52.94 42.74 47.10 54.40

Marc

```