rmatrixmean

Calculate mean of matrices having different dimensions


I have three matrices like these:

m1 <- matrix(c(1,2,3,4), nrow=2, ncol=2,byrow=T)
m2 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow=3, ncol=3,byrow=T)
m3 <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16), nrow=4, ncol=4,byrow=T)

I want to calculate the mean of all these three matrices' values all together. So that the mean will be calculated out of all 29 values from the 3 matrices.


Solution

  • I want to calculate the mean of all these three matrices altogether. So that the mean will be calculated out of all 29 values from the 3 matrices.

    Collect in a list, unlist() and calculate the mean.

    > mean(unlist(list(m1, m2, m3)))
    [1] 6.586207
    

    This can be further customised. Get objects with certain pattern,Filter() for matrix, and unlist().

    > mean(unlist(Filter(is.matrix, mget(ls(pattern = 'm\\d{1}')))))
    [1] 6.586207