在R中的组中查找子组摘要

av *_*iek 0 grouping r summary dplyr

PPG Product Week        Sales
 P1  A      01/01/2018  50
 P1  B      01/01/2018  40
 P1  B      01/02/2018  30
 P1  A      01/02/2018  80
 P2  A      01/01/2018  100
 P2  B      01/02/2018  70
Run Code Online (Sandbox Code Playgroud)

我试图找到每个PPG的总结,在这里和每个PPG中我想要获得最高销售额(整体)的产品,如下所示,

PPG   Max Product Sales
 P1      130 (This is sum of product A for ppg p1 across weeks)
 P2      100 (This is sum of product A for ppg p2 across weeks)
Run Code Online (Sandbox Code Playgroud)

我已经尝试在dplyr中使用top_n(1,sum(sales))来实现,但它失败了,我们怎么能解决这个问题呢?我们可以将它扩展到几周内按销售额找到前n个产品,以检查是否80 -20规则,欢迎任何想法.

cle*_*ens 5

这是一个解决方案dlpyr:

library(dplyr)
Run Code Online (Sandbox Code Playgroud)

首先,按PPG和Product对数据进行分组,按组分类销售,然后按PPG分组,只取最大值:

my_data %>% 
  group_by(PPG, Product) %>% 
  summarise("Max Product Sales" = sum(Sales)) %>% 
  group_by(PPG) %>% 
  summarise("Max Product Sales" = max(`Max Product Sales`))
Run Code Online (Sandbox Code Playgroud)

输出:

# A tibble: 2 x 2
    PPG `Max Product Sales`
  <chr>               <dbl>
1    P1                 130
2    P2                 100
Run Code Online (Sandbox Code Playgroud)

data.table:

library(data.table)
setDT(my_data)

my_data[, .(`Max Product Sales` = sum(Sales)), by = .(PPG, Product)][, .(`Max Product Sales` = max(`Max Product Sales`)), by = PPG]
Run Code Online (Sandbox Code Playgroud)

返回:

   PPG Max Product Sales
1:  P1               130
2:  P2               100
Run Code Online (Sandbox Code Playgroud)