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) ?
colMeans() function in R Language is used to compute the mean of each column of a matrix or array.
Method 1: Using colMeans() function colMeans() this will return the column-wise mean of the given dataframe. where dataframe_name is the input dataframe. For this simply pass the dataframe in use to the colMeans() function. The result will be the mean of all the individual columns.
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
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