1

我有一个数据框(约 5000 行,6 列),其中包含id变量的一些重复值。我有另一个连续变量x,我想为每个重复项求和其值id。观察是时间相关的,存在变量yearmonth我想保持每个重复的时间顺序第一次观察,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)
4

2 回答 2

5

我得到了不同的金额,但它是 b/c 我忘记了种子:

> dat1$x <- ave(dat1$x, dat1$id, FUN=sum)
> dat1[!duplicated(dat1$id), ]
    id year    month     x
1 1234 2006 December 25.18
2 1321 2006 December 15.06
3 4321 2006 December 15.50
4 7423 2006 December  7.16
6 8503 2007  January 13.23
7 2961 2007  January  7.38
9 8564 2007  January  7.21

(为了更安全,最好在副本上工作。您可能需要添加一个订购步骤。)

于 2013-02-08T02:09:40.557 回答
3

你可以用data.table(比 plyr 更快,更有效的内存)来做到这一点

使用mult='first' 带来一点自加入的乐趣。按 id 年和月键入将按 id、年和月排序。

library(data.table)
DT <- data.table(dat1, key = c('id','year','month'))


# setnames is required as there are two x columns that get renamed x, x.1
DT1 <- setnames(DT[DT[,list(x=sum(x)),by=id],mult='first'][,x:=NULL],'x.1','x')

或者更简单的方法:

DT = as.data.table(dat1)

DT[,x:=sum(x),by=id][!duplicated(id)]

     id year    month     x
1: 1234 2006 December 36.42
2: 1321 2006 December 11.55
3: 4321 2006 December 17.31
4: 7423 2006 December  5.97
5: 8503 2007  January 12.48
6: 2961 2007  January 10.22
7: 8564 2007  January 11.41
于 2013-02-08T01:17:37.937 回答