Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mean of each element of a list of matrices

Tags:

r

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.

like image 370
upabove Avatar asked Sep 01 '13 11:09

upabove


People also ask

How do you find the value of each element in a matrix?

The number of elements of a matrix = the number of rows multiplied by the number of columns. For example, if the number of rows is 3 and the number of columns is 4 in a matrix then the number of elements in it is 3 x 4 = 12.

How to calculate the average of matrix?

M = mean( A , vecdim ) computes the mean based on the dimensions specified in the vector vecdim . For example, if A is a matrix, then mean(A,[1 2]) is the mean of all elements in A , since every element of a matrix is contained in the array slice defined by dimensions 1 and 2.

What is element matrix?

Matrix element (physics), the value of a linear operator (especially a modified Hamiltonian) in quantum theory. Matrix coefficient, a type of function in representation theory. Element (software), free and open-source software instant messaging client implementing the Matrix protocol.


1 Answers

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
like image 184
Jilber Urbina Avatar answered Sep 28 '22 06:09

Jilber Urbina