15

R中是否有任何快速方法或内置函数来计算基于第三维的平均值?

例如我的数组是:

, , 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

我的输出是:

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

谢谢!

4

1 回答 1

26

?apply是这些类型任务的朋友。

# 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)
于 2012-10-24T22:52:49.307 回答