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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With