Search code examples
r

Calculating mean of multiple matrices


What's an efficient way to calculate mean of multiple matrices of same dimension ?

If A, B are 2 x 2 matrix then,

A
2  3
4  5

B
6  7
8  9

mean(A, B) should give

4  5
6  7

Plain approach is to do (A + B + ...)/num of matrices. (and handle NA values explicitly)

Any other elegant approach or library to do this (with support of na.rm) ?


Solution

  • Combine them into an array and use apply:

    A <- matrix(c(2,4,3,5), 2)
    B <- matrix(c(6,8,7,9), 2)
    
    X <- list(A, B)
    Y <- do.call(cbind, X)
    Y <- array(Y, dim=c(dim(X[[1]]), length(X)))
    
    apply(Y, c(1, 2), mean, na.rm = TRUE)
    #     [,1] [,2]
    #[1,]    4    5
    #[2,]    6    7
    

    If apply is not efficient enough, you can use colMeans (which provides NA handling) with aperm:

    colMeans(aperm(Y, c(3, 1, 2)), na.rm = TRUE)
    #     [,1] [,2]
    #[1,]    4    5
    #[2,]    6    7