Search code examples
arraysrcomputation

How to calculate the mean by index of N elements in an array in R


I have a generic array of 15 elements. Each element in this array is a 159 by 159 matrix.

Now, I want to calculate the mean of of each index across 15 elements and store the result in a new 159 by 159 matrix, which has the new index resulting from the mean of the same index position over 15 elements of the original array.

This is a nested array if I am allowed to say so. This is also an EigenFace problem on an open source site that I found interesting. So, long story short, this array is a collection of 15 people, and each person has 11 images taken with 11 facial emotions such as wink, happy, sad, etc. So it is an array of 15 elements, each element is also an array of 11 rows and thousands of columns of pixels to portray the facial expression of that person.

For instance, the new index [1,1] of the new matrix is obtained by taking the mean of [1,1] indexes from 15 elements/matrices in the original array.

I would like to avoid using the for loop and hope that there is a built-in function which I can utilize.

Any tips would be greatly appreciated!


Solution

  • You could use Reduce():

    data <- list(matrix(1:16, 4), matrix(1:16, 4))
    
    result <- Reduce('+', data)
    
    result <- result * 1/length(data)