How to average the same cells over many lists of matrices in R

Viewed 115

I would like to average the same cells in multiple lists of matrices and the result be a matrix with averaged cells. e.g.

x <- list()
x[[1]] <- data.frame(matrix(sample(1:7,16, replace = T),4,4))
x[[2]] <- data.frame(matrix(sample(1:7,16, replace = T),4,4))

> x[[2]]
  X1 X2 X3 X4
1  3  5  2  6
2  4  2  5  1
3  7  7  3  3
4  7  4  7  1
> x[[1]]
  X1 X2 X3 X4
1  6  5  2  7
2  7  2  7  7
3  3  5  7  1
4  5  4  1  7

I would like a 4x4 matrix with each entry the average of the same entry of the two lists.

Thanks

2 Answers

Use as.matrix on the output if you want a matrix class object instead of a data.frame

Reduce('+', x)/length(x)

An option is also with apply and mean if we convert to array. mean can take care of NA elements with na.rm = TRUE

apply(array(unlist(x), c(dim(x[[1]]), length(x))), 1:2, mean, na.rm = TRUE)
#     [,1] [,2] [,3] [,4]
#[1,]  3.0  3.5  2.5  1.5
#[2,]  3.5  5.0  5.0  3.5
#[3,]  3.5  4.5  5.5  6.5
#[4,]  4.0  4.0  3.5  4.5

Or using rowMeans

t(apply(array(unlist(x), c(dim(x[[1]]), length(x))), 1, rowMeans, na.rm = TRUE))
#    [,1] [,2] [,3] [,4]
#[1,]  3.0  3.5  2.5  1.5
#[2,]  3.5  5.0  5.0  3.5
#[3,]  3.5  4.5  5.5  6.5
#[4,]  4.0  4.0  3.5  4.5
Related