R - 为重复购买分组日期和汇总数据

R - Grouping Dates and Summarizing Data for repeat purchase

我正在尝试对客户的重复购买行为进行分析。

我的目标有两个:

  1. 消除所有只出现一次的客户物品邮编组合(消除不重复的)
  2. 对于重复的记录,我想总结相同的地方,我需要获得多个订单之间的平均天数以及总销售额

如果我有以下数据:

Customer#   Item        Zip     Date            Qty     Net Sales
---------   --------    -----   ----------      ---     ---------
ABC123      GHTH123     76137   2014-01-01      10      1500
XYZ999      ZZZZZZZ     68106   2015-02-01      1       50
DEF456      167AAAA     60018   2015-03-01      12      650
XYZ999      YYYYYYY     68106   2015-01-01      3       150 
XYZ999      ZZZZZZZ     68106   2015-04-01      10      500
XYZ999      YYYYYYY     68106   2015-03-01      12      600
XYZ999      YYYYYYY     68106   2015-05-01      10      500 
ABC123      GHTH123     76137   2014-01-15      8       1200
ABC234      N867689     23218   2014-01-01      10      1500
ABC123      DDFF121     76137   2014-01-27      15      2250

我正在尝试获得以下输出:

Customer#   Item        Zip     Avg Days/Ord    Tot Ord     Total Amt
---------   --------    -----   ----------      -------     ---------
ABC123      GHTH123     76137   15              2           2700
XYZ999      ZZZZZZZ     68106   60              2           550
XYZ999      YYYYYYY     68106   60              3           1250

我试图使用 sqldiff 包并使用 DATEDIFF 函数,但我没有得到任何结果,因为 DATEDIFF 不适用于 R

有人可以帮我找到更好的方法吗?

你可以试试

library(dplyr)
df1 %>% 
    group_by(Customer, Item, Zip) %>%
    filter(n()>1) %>% 
    summarise(AvgDays=mean(diff(Date)),TotOrd= n(), TotAmt=sum(NetSales))
#   Customer    Item   Zip AvgDays TotOrd TotAmt
#1   ABC123 GHTH123 76137      14      2   2700
#2   XYZ999 ZZZZZZZ 68106      59      2    550
#3   XYZ999 YYYYYYY 68106      60      3   1250

或者

library(data.table)
setDT(df1)[, if(.N>1) list(AvgDays= mean(c(diff(Date))), TotOrd=.N, 
                  TotAmt=sum(NetSales)), .(Customer, Item, Zip)] 
#   Customer    Item   Zip AvgDays TotOrd TotAmt
#1:   ABC123 GHTH123 76137      14      2   2700
#2:   XYZ999 ZZZZZZZ 68106      59      2    550
#3:   XYZ999 YYYYYYY 68106      60      3   1250