Search code examples
r

Mean of each element of a list of matrices


I have a list with three matrixes:

a<-matrix(runif(100))
b<-matrix(runif(100))
c<-matrix(runif(100))

mylist<-list(a,b,c)

I would like to obtain the mean of each element in the three matrices.

I tried: aaply(laply(mylist, as.matrix), c(1, 1), mean) but this returns the means of each matrix instead of taking the mean of each element as rowMeans() would.


Solution

  • Maybe what you want is:

    > set.seed(1)
    > a<-matrix(runif(4)) 
    > b<-matrix(runif(4))
    > c<-matrix(runif(4))
    > mylist<-list(a,b,c)  # a list of 3 matrices 
    > 
    > apply(simplify2array(mylist), c(1,2), mean)
              [,1]
    [1,] 0.3654349
    [2,] 0.4441000
    [3,] 0.5745011
    [4,] 0.5818541
    

    The vector c(1,2) for MARGIN in the apply call indicates that the function mean should be applied to rows and columns (both at once), see ?apply for further details.

    Another alternative is using Reduce function

    > Reduce("+", mylist)/ length(mylist)
              [,1]
    [1,] 0.3654349
    [2,] 0.4441000
    [3,] 0.5745011
    [4,] 0.5818541