gpt4 book ai didi

r - 获取每个客户每天的运行计数

转载 作者:行者123 更新时间:2023-12-04 10:39:34 25 4
gpt4 key购买 nike

我有一个像这样的表:

ppp<-data.frame(client=c(1,1,1,3,3), 
calldate=c('2014-08-07', '2014-08-09','2014-08-06','2014-08-07', '2014-08-08'),
cant=c(1,2,3,2,1))

我需要计算每个客户几天来的累积总和。在这种情况下,我需要得到下表:

client    calldate   cant   cum cant
1 06/08/2014 3 3
1 07/08/2014 1 4
1 09/08/2014 2 6
2 07/08/2014 2 2
2 08/08/2014 1 3

我试过了,我得到了正确的解决方案:

ppp <- ppp[order(ppp$client,ppp$calldate),]
ppp$cumsum<-unlist(tapply(ppp$cant,ppp$client,FUN=cumsum))

但这是最好的方法吗?为每个客户创建一个列表,然后取消列出该列表? 另外,因为我没有指定日期字段,所以我只对数据进行排序。

最佳答案

或者一个data.table选项

library(data.table) # 1.9.4+
setorder(setDT(ppp), client, calldate)[, cum_cant := cumsum(cant), by = client]
ppp
# client calldate cant cum_cant
# 1: 1 2014-08-06 3 3
# 2: 1 2014-08-07 1 4
# 3: 1 2014-08-09 2 6
# 4: 3 2014-08-07 2 2
# 5: 3 2014-08-08 1 3

编辑:对于旧的 data.table 版本 (< 1.9.4) 使用 setkey 而不是 setorder

setkey(setDT(ppp), client, calldate)[, cum_cant := cumsum(cant), by = client]

编辑 #2(根据 OP 评论):

setkey(setDT(ppp), client, calldate)[, `:=`(cum_cant = cumsum(cant),
cummin_cant = cummin(cant)), by = client]

关于r - 获取每个客户每天的运行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26534350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com