Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating mean of multiple matrices in R

Tags:

r

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) ?

like image 914
Mohit Verma Avatar asked Sep 24 '14 09:09

Mohit Verma


People also ask

How do you find the mean of a matrix in R?

colMeans() function in R Language is used to compute the mean of each column of a matrix or array.

How do you calculate mean for all columns in R?

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.


1 Answers

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
like image 166
Roland Avatar answered Oct 01 '22 01:10

Roland