Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mean on the third dimension in R

Tags:

r

Is there any quick way or build-in function in R to calculation the mean values based on the third dimension?

For example my array is:

, , 1
     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2
    [,1] [,2]
[1,]   11   13
[2,]   12   14

, , 3
     [,1] [,2]
[1,]   21   23
[2,]   22   24

My output would be:

            [,1]        [,2]
[1,]   mean(1,11,21)   mean(3,13,23)
[2,]   mean(2,12,22)   mean(4,14,24)

Thanks!

like image 659
TTT Avatar asked Oct 24 '12 22:10

TTT


People also ask

How to declare 3 dimensional array in R?

Create 3D array using the dim() function in R Arrays in R Programming Language are the data objects which can store data in more than two dimensions. 3-D array is also known as a Multidimensional array. We can create a multidimensional array with dim() function.

How do you find the mean of an array in R?

Calculate the Mean of each Column of a Matrix or Array in R Programming – colMeans() Function. colMeans() function in R Language is used to compute the mean of each column of a matrix or array. dims: integer value, which dimensions are regarded as 'columns' to sum over. It is over dimensions 1:dims.


1 Answers

?apply is your friend for these types of tasks.

# Make the sample data
j <- array(c(1:4, 11:14, 21:24), c(2,2,3))
# For each combination in the 1st and 2nd dimension
# average over the values in the 3rd.
apply(j, c(1,2), mean)
like image 53
Dason Avatar answered Oct 04 '22 23:10

Dason