Mean of each element of a list of matrices

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

Leave a Comment