4

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

我的数据格式如下:

原始数据

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

我想得到什么

我正在考虑将数据与以下内容进行分组:

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

或者

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

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

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

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

1 回答 1

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

在这两种解决方案中,关键是创建一个“时间”变量,该变量由“类型”和可以用ave.

为了完整起见,这里dcast来自“reshape2”:

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
于 2013-01-28T05:13:04.130 回答