合并同一人同一天的交易
Combining transactions from the same people on the same day
情况:我有一个包含交易的数据集 (transData)。每笔交易都有自己的行,其中有相关的列:transactionID、customerID、Date 和 moneySpend.
简化示例:
1; 101; 1/1/18; 42
2; 101; 1/1/18; 13
3; 102; 1/1/18; 32
4; 103; 1/1/18; 56
5; 103; 1/1/18; 85
6; 103; 2/1/18; 8
7; 101; 2/1/18; 23
8; 103; 2/1/18; 14
9; 103; 2/1/18; 35
10; 104; 2/1/18; 48
我需要什么:单个客户每天可以购买多件商品,但是每件商品在交易数据集中都有自己的行。但是,我需要将这些交易组合成一个交易,其中 moneySpend 是各个项目的总和。
简化示例:
1; 101; 1/1/18; 55
2; 102; 1/1/18; 32
3; 103; 1/1/18; 141
4; 103; 2/1/18; 77
5; 101; 2/1/18; 23
6; 104; 2/1/18; 48
(注:transactionID不重要,唯一即可。)
我所做的:使用 plyr 包中的 ddply,我创建了一个 table 来整理 customerId 和 day 的异常组合:
newTable <- ddply(transData, .(transData$customerID, transData$Date), nrow)
接下来我在for循环中总结交易:
for (i in 1:dim(newTable)[1]){
trans = which(transData$customerID==newTable[i,1] & transData$Date==newTable[i,2])
totalSpend[i]=sum(transData[trans,32:35])
}
问题:对于需要处理的交易量而言,这太慢了。
有没有办法更有效地做到这一点?
在data.table中,只需:
transData[, newVar := sum(moneySpend), by = c("customerID", "Date")]
我根据此处的一些评论使用 dplyr 包找到了解决方案。
transactions = transData %>%
group_by(customerID,Date) %>%
summarise(moneySpend = sum(moneySpend))
感谢您的思考。
情况:我有一个包含交易的数据集 (transData)。每笔交易都有自己的行,其中有相关的列:transactionID、customerID、Date 和 moneySpend.
简化示例:
1; 101; 1/1/18; 42
2; 101; 1/1/18; 13
3; 102; 1/1/18; 32
4; 103; 1/1/18; 56
5; 103; 1/1/18; 85
6; 103; 2/1/18; 8
7; 101; 2/1/18; 23
8; 103; 2/1/18; 14
9; 103; 2/1/18; 35
10; 104; 2/1/18; 48
我需要什么:单个客户每天可以购买多件商品,但是每件商品在交易数据集中都有自己的行。但是,我需要将这些交易组合成一个交易,其中 moneySpend 是各个项目的总和。
简化示例:
1; 101; 1/1/18; 55
2; 102; 1/1/18; 32
3; 103; 1/1/18; 141
4; 103; 2/1/18; 77
5; 101; 2/1/18; 23
6; 104; 2/1/18; 48
(注:transactionID不重要,唯一即可。)
我所做的:使用 plyr 包中的 ddply,我创建了一个 table 来整理 customerId 和 day 的异常组合:
newTable <- ddply(transData, .(transData$customerID, transData$Date), nrow)
接下来我在for循环中总结交易:
for (i in 1:dim(newTable)[1]){
trans = which(transData$customerID==newTable[i,1] & transData$Date==newTable[i,2])
totalSpend[i]=sum(transData[trans,32:35])
}
问题:对于需要处理的交易量而言,这太慢了。
有没有办法更有效地做到这一点?
在data.table中,只需:
transData[, newVar := sum(moneySpend), by = c("customerID", "Date")]
我根据此处的一些评论使用 dplyr 包找到了解决方案。
transactions = transData %>%
group_by(customerID,Date) %>%
summarise(moneySpend = sum(moneySpend))
感谢您的思考。