三维数组的边际摘要

时间:2013-09-22 20:28:36

标签: r aggregate mean summarization

我正在使用以“R转储”格式输出数据的系统。例如,它可能会输出如下所示的三维数组:

obs <- structure(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24), 
          .Dim=c(2,4,3))

我是R的新手,但我想用R来检查这些数据的边缘摘要。例如,我希望看到在第三维平均值上的2x4平均值表。

(如果可能的话,我还希望看到边缘摘要折叠到一个维度,例如一行4个平均值,每个意味着取代我的数据的2x3切片。)

我尝试summary(obs)折叠所有维度并提供整体统计数据,sapply(obs, summary)不会折叠任何维度,只是给出每个单独数据的“摘要”。

我希望有一个功能可以解决我的问题,但我找不到它!

2 个答案:

答案 0 :(得分:3)

apply适用于此:

 apply(obs,1:2,mean)
     [,1] [,2] [,3] [,4]
[1,]    9   11   13   15
[2,]   10   12   14   16

aperm(apply(obs,1:2,summary),c(1,3,2))

(或评论中指出的apply(obs,2:1,summary)

结果:

        [,1] [,2] [,3] [,4]
Min.       1    3    5    7
1st Qu.    5    7    9   11
Median     9   11   13   15
Mean       9   11   13   15
3rd Qu.   13   15   17   19
Max.      17   19   21   23

, , 2

        [,1] [,2] [,3] [,4]
Min.       2    4    6    8
1st Qu.    6    8   10   12
Median    10   12   14   16
Mean      10   12   14   16
3rd Qu.   14   16   18   20
Max.      18   20   22   24

根据要求,您可以获得其他边际摘要

apply(obs,2,mean)
## [1]  9.5 11.5 13.5 15.5

(仔细检查:mean(obs[,1,])确实是9.5 ......)

答案 1 :(得分:3)

在挖掘R工具箱时,您可能还希望查看plyr工具:a*ply。该函数以array作为输入,并且很容易控制返回结果的形式:数组,数据框或列表。

为了让我们在使用示例数组时更容易跟踪尺寸,我添加了一些任意尺寸名称。第一维(行)=物种;秒(列)=时间;第三个(单独的'tables')= site

obs <- array(c(1:24), 
         dim = c(2, 4, 3),
         dimnames = list(species = c("cat", "dog"),
                         time = 1:4,
                         site = letters[1:3]))

library(plyr)
# result as (2-d) array: aaply
# i.e. same output as @Ben Bolker's `apply` example
# keep the first two dimensions (species, time), collapse the third (site)
aaply(obs, 1:2, mean)

#         time
# species  1  2  3  4
#     cat  9 11 13 15
#     dog 10 12 14 16

# result as data frame: adply
adply(obs, 1:2, mean)

#   species time V1
# 1     cat    1  9
# 2     dog    1 10
# 3     cat    2 11
# 4     dog    2 12
# 5     cat    3 13
# 6     dog    3 14
# 7     cat    4 15
# 8     dog    4 16

# several functions
adply(obs, 1:2, each(min, mean, max))
#   species time min mean max
# 1     cat    1   1    9  17
# 2     dog    1   2   10  18
# 3     cat    2   3   11  19
# 4     dog    2   4   12  20
# 5     cat    3   5   13  21
# 6     dog    3   6   14  22
# 7     cat    4   7   15  23
# 8     dog    4   8   16  24

# apparently the `each` thing can be used on just one function as well,
# then the function name appears as column name instead of 'V1' as above.
adply(obs, 1:2, each(mean))
#   species time mean
# 1     cat    1    9
# 2     dog    1   10
# 3     cat    2   11
# 4     dog    2   12
# 5     cat    3   13
# 6     dog    3   14
# 7     cat    4   15
# 8     dog    4   16

# one-dimensional summary    
adply(obs, 2, each(mean))
#   time mean
# 1    1  9.5
# 2    2 11.5
# 3    3 13.5
# 4    4 15.5