【问题标题】:calculation sum separately by groups in RR中按组分别计算总和
【发布时间】:2018-06-28 11:26:56
【问题描述】:

说,我有数据集。

df=structure(list(ItemRelation = c(13250L, 13250L, 13250L, 13250L, 
13250L, 13250L, 13250L, 13250L, 13250L, 13250L, 13250L, 13250L, 
1300L, 1300L, 1300L, 1300L, 1300L, 1300L, 1300L, 1300L, 1300L, 
1300L, 1300L, 1300L), SaleCount = c(354L, 679L, 397L, 473L, 614L, 
404L, 127L, 434L, 786L, 127L, 434L, 786L, 354L, 679L, 397L, 473L, 
614L, 404L, 127L, 434L, 786L, 127L, 434L, 786L), DocumentNum = c(336L, 
336L, 336L, 336L, 336L, 336L, 336L, 336L, 336L, 336L, 336L, 336L, 
335L, 335L, 335L, 335L, 335L, 335L, 335L, 335L, 335L, 335L, 335L, 
335L), IsPromo = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 
1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L)), .Names = c("ItemRelation", 
"SaleCount", "DocumentNum", "IsPromo"), class = "data.frame", row.names = c(NA, 
-24L))

有变量ispromo。它只取值 0 和 1。 所以,我必须分别计算每个组的销售额总和,但仅限于 1 类 ispromo。 分组是 ItemRelation +SaleCount +DocumentNum

我该怎么做?

想要的输出

ItemRelation    DocumentNum sum1
13250            336       1347
1300             335       1347

【问题讨论】:

    标签: r dplyr plyr lapply


    【解决方案1】:

    使用 dplyr:

    library(dplyr)
    
    df %>% 
      group_by(ItemRelation, DocumentNum) %>% 
      filter(IsPromo == 1) %>% 
      summarise(sum1 = sum(SaleCount))
    
    # A tibble: 2 x 3
    # Groups:   ItemRelation [?]
      ItemRelation DocumentNum  sum1
             <int>       <int> <int>
    1         1300         335  1347
    2        13250         336  1347
    

    【讨论】:

      【解决方案2】:

      这是使用aggregate 的补充性基础 R 解决方案

      aggregate(SaleCount ~ ItemRelation + DocumentNum, subset(df, IsPromo == 1), sum)
      #  ItemRelation DocumentNum SaleCount
      #1         1300         335      1347
      #2        13250         336      1347
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 2020-04-15
        • 2021-12-16
        • 2017-01-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多