Mean on the third dimension in R

2020-08-13 07:41发布

问题:

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!

回答1:

?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)


标签: r