另一个聚合

时间:2013-01-28 04:53:37

标签: r aggregate reshape

(对不起,如果标题不是很有用:我不知道如何更好地定义这个问题)

我的数据如下:

original data

在每个组中,我有一个pre值和一个或两个post值。我想将此表转换为以下内容:

what I would like to get

我正在考虑将数据分组为:

aggregate(mydata, by = group, FUN = myfunction)

ddply(mydata, .(group), .fun = myfunction)

并在我的函数中处理每个组的元素。但我不知道如何做到这一点因为我需要同时将typevalue传递给我的函数。有更好的方法吗?

更新:快速而脏的样本数据集:

mydata <- data.frame(group = sample(letters[1:5], 10, replace = TRUE), 
                     type = sample(c("pre", "post"), 10, replace = TRUE), 
                     value = rnorm(10))

1 个答案:

答案 0 :(得分:8)

尝试这样的事情:

mydf <- data.frame(group = c("A", "A", "B", "B",
                             "C", "C", "C", "D",
                             "D", "E", "E"),
                   type = c("pre", "post", "pre",
                            "post", "pre", "post",
                            "post", "pre", "post",
                            "pre", "post"),
                   value = 1:11)

times <- with(mydf, ave(value, group, type, FUN = seq_along))
xtabs(value ~ group + interaction(type, times), mydf)
#      interaction(type, times)
# group post.1 pre.1 post.2 pre.2
#     A      2     1      0     0
#     B      4     3      0     0
#     C      6     5      7     0
#     D      9     8      0     0
#     E     11    10      0     0

或者:

times <- with(mydf, ave(value, group, type, FUN = seq_along))  
mydf$timevar <- interaction(mydf$type, times)
reshape(mydf, direction = "wide", idvar = "group", 
        timevar="timevar", drop="type")
#    group value.pre.1 value.post.1 value.post.2
# 1      A           1            2           NA
# 3      B           3            4           NA
# 5      C           5            6            7
# 8      D           8            9           NA
# 10     E          10           11           NA

在两个解决方案中,关键是创建一个“时间”变量,由“type”和可以使用ave创建的序列变量的组合表示。

为了完整性,这里是来自“reshape2”的dcast

times <- with(mydf, ave(value, group, type, FUN = seq_along))
library(reshape2)
dcast(mydf, group ~ type + times)
#   group post_1 post_2 pre_1
# 1     A      2     NA     1
# 2     B      4     NA     3
# 3     C      6      7     5
# 4     D      9     NA     8
# 5     E     11     NA    10