Question

I wish to obtain the mean value for every element in an array. In a simple example, let's say we have this simple array:

, , 1

              [,1]          [,2]          [,3]
 [1,]  2.000000000  3.000000000   1.000000000
 [2,]  6.000000000  5.000000000   2.000000000
 [3,]  8.000000000  12.00000000   4.000000000
 [4,]  12.00000000  10.00000000   4.000000000

, , 2

              [,1]          [,2]          [,3]
 [1,]  4.000000000  6.000000000   2.000000000
 [2,]  4.000000000  10.00000000   3.000000000
 [3,]  8.000000000  12.00000000   4.000000000
 [4,]  8.000000000  20.00000000   6.000000000

, , 3

              [,1]          [,2]          [,3]
 [1,]  6.000000000  9.000000000   3.000000000
 [2,]  2.000000000  15.00000000   4.000000000
 [3,]  12.00000000  18.00000000   6.000000000
 [4,]  4.000000000  30.00000000   8.000000000

I want to find the mean of every row i, column i across all tables(?) in the array. In the above case the correct result would be this matrix (sorry, I'm not very good at making up numbers):

              [,1]          [,2]          [,3]
 [1,]  4.000000000  6.000000000   2.000000000
 [2,]  6.000000000  10.00000000   3.000000000
 [3,]  8.000000000  12.00000000   4.000000000
 [4,]  12.00000000  20.00000000   6.000000000

I can do the arithmetic 'by hand':(my.array[,,1]+my.array[,,2]+my.array[,,3])/3 That gives a single matrix with the mean of each element. However, my data has many NA values, and a function like mean() ought to allow me to use a na.rm=TRUE argument to deal with these missing values.

Obviously you can use mean(my.array[i,i,] to average each element across all tables, but is there an easy way to do all elements at once and spit out a matrix? I thought apply() would be a good bet but I haven't yet found the right expression.

Was it helpful?

Solution

You are looking for this:

apply(data, 1:2, mean)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top