【问题标题】:Sum Groups of Observations in R Data Frame (Group by similar values) [duplicate]汇总 R 数据框中的观察组(按相似值分组)[重复]
【发布时间】:2016-06-16 07:05:14
【问题描述】:

数据框由变量DateTypeTotal组成,其中TypeBuySell

我们如何对观察进行分组,以便仅将相同Type 的相邻观察分组在一起,然后将每组中所有观察的Total 相加。换句话说,我们不断将下一个观察添加到当前组,直到 Type 的值发生变化。

例如,在下面的数据框中,分组如下

  • 观察员1 & 2
  • 观察员3 & 4
  • 观察员5 & 6
  • 观察员7, 8 & 9

可重复的数据,谢谢@bgoldst:

df1 <- data.frame(Date=rep(as.POSIXct('2016-06-16 06:27:39'),9L),
                  Type=c('Buy','Buy','Sell','Sell','Buy','Buy','Sell','Sell','Sell'),
                  Total=c(1.548012e+01,1.051480e+02,5.956740e+00,3.872415e+01,1.333391e+02,1.941060e-01,1.941060e-01,1.941060e-01,3.277059e-01))

【问题讨论】:

  • 请尽量避免图片数据。一个可重现的例子更有帮助。

标签: r dataframe


【解决方案1】:

这是一个围绕aggregate() 构建的略显丑陋的基础 R 解决方案。它使用Typecumsum()的连续元素之间的不等比较来合成一个瞬态分组列来区分Type的非连续实例。

df <- data.frame(Date=rep(as.POSIXct('2016-06-16 06:27:39'),9L),Type=c('Buy','Buy','Sell','Sell','Buy','Buy','Sell','Sell','Sell'),Total=c(1.548012e+01,1.051480e+02,5.956740e+00,3.872415e+01,1.333391e+02,1.941060e-01,1.941060e-01,1.941060e-01,3.277059e-01));
aggregate(Total~Date+Type+TypeSeq,transform(df,TypeSeq=c(0L,cumsum(Type[-1L]!=Type[-nrow(df)]))),sum)[-3L];
##                  Date Type       Total
## 1 2016-06-16 06:27:39  Buy 120.6281200
## 2 2016-06-16 06:27:39 Sell  44.6808900
## 3 2016-06-16 06:27:39  Buy 133.5332060
## 4 2016-06-16 06:27:39 Sell   0.7159179

用 data.table 实现相同的想法:

library(data.table);
dt <- as.data.table(df);
dt[,.(Total=sum(Total)),.(Date,Type,TypeSeq=c(0L,cumsum(Type[-1L]!=Type[-nrow(dt)])))][,-3L,with=F];
##                   Date Type       Total
## 1: 2016-06-16 06:27:39  Buy 120.6281200
## 2: 2016-06-16 06:27:39 Sell  44.6808900
## 3: 2016-06-16 06:27:39  Buy 133.5332060
## 4: 2016-06-16 06:27:39 Sell   0.7159179

【讨论】:

【解决方案2】:

使用data.table 的简单解决方案(最新稳定版,CRAN 上的 v1.9.6):

require(data.table)
# Create group id *and* aggregate in one-go using expressions in 'by'
setDT(df)[, .(total = sum(Total)), by=.(group=rleid(Type), Date)]

#    group                Date       total
# 1:     1 2016-06-16 06:27:39 120.6281200
# 2:     2 2016-06-16 06:27:39  44.6808900
# 3:     3 2016-06-16 06:27:39 133.5332060
# 4:     4 2016-06-16 06:27:39   0.7159179

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 2023-03-07
    • 2023-03-31
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多