aaaaa
aaaaa

Reputation: 185

Mean of multiple dimensions' observations within array

I have got an array as follows:

ar.1 = array(1:12, dim=c(2,2,3))

> ar.1
, , 1

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

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

, , 3

     [,1] [,2]
[1,]    9   11
[2,]   10   12

I just need to compute the mean between the values in the 3 different layers and obtain a 2-dimensional matrix.

Expected output:

5  7  
6  8


5 = (1+5+9) / 3
6 = (2+6+10) / 3
etc..

It should be really easy but I couldn't find any quick solution yet as my real array is larger than 2x2x3.

Thanks

Upvotes: 1

Views: 45

Answers (1)

989
989

Reputation: 12937

Try this

matrix(rowMeans(apply(ar.1, 3, c)), dim(ar.1)[1], dim(ar.1)[2])

#      [,1] [,2]
#[1,]    5    7
#[2,]    6    8

Upvotes: 1

Related Questions