【问题标题】:How to group customer orders by date [duplicate]如何按日期对客户订单进行分组[重复]
【发布时间】:2020-07-31 08:35:45
【问题描述】:

我有一个包含如下客户订单数据的数据框:

cust    order number     order_date      total   product_id
 1      1235846868       2020-01-27       20.0   Product A
 1      1235846869       2020-01-27       14.0   Product B
 2      1245485221       2020-05-16       11.1   Product B, Product C, Product D
 3      1285784226       2020-07-10       24.0   Product D
 4      5412151256       2020-03-27       12.0   Product A
 4      5412151290       2020-04-13       23.0   Product C, Product B
 5      5481581554       2020-02-18       12.0   Product D

正如您在上面看到的,有些客户(例如客户“1”)在同一天多次订购(可能是因为他们在第一次订购时忘记在他们的 basked 中放东西)。我想在同一天汇总客户的这些多个订单,但保留我在数据集中拥有的所有其他列(例如 product_id、order_number 等)。输出表应如下所示:

cust    order number                order_date      total   product_id
 1      1235846868, 1235846869      2020-01-27       34.0   Product A, Product B
 2      1245485221                  2020-05-16       11.1   Product B, Product C, Product D
 3      1285784226                  2020-07-10       24.0   Product D
 4      5412151256                  2020-03-27       12.0   Product A
 4      5412151290                  2020-04-13       23.0   Product C, Product B
 5      5481581554                  2020-02-18       12.0   Product D

谢谢!

【问题讨论】:

    标签: r group-by aggregate


    【解决方案1】:

    使用dplyr 的一种方法是sum total 列并为order_numberproduct_id 列创建一个逗号分隔的字符串。

    library(dplyr)
    
    df %>%
      group_by(cust, order_date) %>%
      summarise(total = sum(total, na.rm = TRUE), 
                across(c(order_number, product_id), toString))
    
    #  cust order_date total order_number           product_id                
    #  <int> <chr>      <dbl> <chr>                  <chr>                     
    #1     1 2020-01-27  34   1235846868, 1235846869 ProductA, ProductB        
    #2     2 2020-05-16  11.1 1245485221             ProductB,ProductC,ProductD
    #3     3 2020-07-10  24   1285784226             ProductD                  
    #4     4 2020-03-27  12   5412151256             ProductA                  
    #5     4 2020-04-13  23   5412151290             ProductC,ProductB         
    #6     5 2020-02-18  12   5481581554             ProductD       
    

    【讨论】:

    • 嗨罗纳克!再次感谢您的快速回复!我会立即尝试!还有一个问题:我的数据集由 30 列组成 - 是否也有一种更短的方法来聚合这些列,或者你会说我需要总结每一列吗?谢谢!
    • 您可以使用across,如答案所示。您可以根据位置(2 到 5)、列范围(A 到 D)或名称中的模式(以 A 等开头)选择多列。
    • 谢谢!我现在正在运行代码,但不幸的是,由于数据集大小(> 200 万次观察),我再次认为它需要很长时间。对于上面的代码,您是否可以想到替代方案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多