【发布时间】:2021-12-29 05:16:29
【问题描述】:
我有一个数据集,其中包含客户 ID、他/她订购商品的日期和他/她的发票金额。下面的可重现示例:
client_id_ex<-c("0001","0001","0001","0001","0002","0002","0002","0002","0002","0002","0002")
order_date_ex<-as.Date(c("12-05-2000","02-01-2001","11-11-2020","03-05-2021","12-05-2000","16-05-2000","12-06-2000","13-08-2000","19-05-2004","12-09-2007","08-12-2008"),format="%d-%m-%Y")
invoice_ex<-c(450,100,200,330,543,665,334,753,234,541,1000)
df<-data.frame(client_id_ex,order_date_ex,invoice_ex)
我想分别计算每个客户的发票的移动平均值,以及计算每个订单前不早于 5 年的订单的平均值。
结果如下所示:
client_id_ex order_date_ex invoice_ex avg_invoice_5
1 12.05.2000 450 450
1 02.01.2001 100 275
1 11.11.2020 200 200
1 03.05.2021 330 265
2 12.05.2000 543 543
2 16.05.2000 665 604
2 12.06.2000 334 514
2 13.08.2000 753 574
2 19.05.2004 234 506
2 12.09.2007 541 388
2 08.12.2008 999 591
有人知道怎么做吗?我尝试使用:Calculate average based on date range in R,但由于我必须计算更像移动平均线的东西并分别为每个客户执行此操作,因此我没有从这个示例中得到太多。
【问题讨论】:
标签: r date moving-average