Calculating mean of multiple matrices in R
Update: anyone preferring base-R will want Reduce
instead (please upvote @thelatemail below):
Reduce(`+`, x) / length(x)
Original:
I think there's a better solution to this now, courtesy of purrr::reduce
.
require(purrr)
x = list(volcano+10, volcano-15, volcano-5)
v = reduce(x, `+`) / length(x)
image(v)
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