【发布时间】:2013-02-08 01:00:55
【问题描述】:
我有一个数据框(约 5000 行,6 列),其中包含 id 变量的一些重复值。我有另一个连续变量x,我想为每个重复的id 求和其值。观察是时间相关的,有year 和month 变量,我想保留每个重复id 的时间顺序第一次观察,并将随后的欺骗添加到第一次观察中。
我已包含类似于我所拥有的虚拟数据:dat1。我还包含了一个数据集,显示了我想要的结果的结构:outcome。
我尝试了两种策略,但都不能满足我的需求(见下文)。第一个策略为我提供了 x 的正确值,但我丢失了年份和月份列 - 我需要为所有第一个重复的 id 值保留这些值。第二种策略没有正确总结 x 的值。
任何关于如何获得我想要的结果的建议将不胜感激。
# dummy data set
set.seed(179)
dat1 <- data.frame(id = c(1234, 1321, 4321, 7423, 4321, 8503, 2961, 1234, 8564, 1234),
year = rep(c("2006", "2007"), each = 5),
month = rep(c("December", "January"), each = 5),
x = round(rnorm(10, 10, 3), 2))
# desired outcome
outcome <- data.frame(id = c(1234, 1321, 4321, 7423, 8503, 2961, 8564),
year = c(rep("2006", 4), rep("2007", 3)),
month = c(rep("December", 4), rep("January", 3)),
x = c(36.42, 11.55, 17.31, 5.97, 12.48, 10.22, 11.41))
# strategy 1:
library(plyr)
dat2 <- ddply(dat1, .(id), summarise, x = sum(x))
# strategy 2:
# partition into two data frames - one with unique cases, one with dupes
dat1_unique <- dat1[!duplicated(dat1$id), ]
dat1_dupes <- dat1[duplicated(dat1$id), ]
# merge these data frames while summing the x variable for duplicated ids
# with plyr
dat3 <- ddply(merge(dat1_unique, dat1_dupes, all.x = TRUE),
.(id), summarise, x = sum(x))
# in base R
dat4 <- aggregate(x ~ id, data = merge(dat1_unique, dat1_dupes,
all.x = TRUE), FUN = sum)
【问题讨论】: