【发布时间】:2018-09-08 20:14:01
【问题描述】:
我目前正在尝试创建一个累积总和列,该列将基于 Game_ID 创建一个累积总和,但只计算一次与 Game_ID 相关的值。例如,玩家 A 在 Game_ID == 1 中进行了 20 次射击,在 Game_ID == 2 中进行了 13 次射击。对于累积总和,我希望 Shot_Count 值(基于 Game_ID)仅计算一次,尽管出现在 Shot_Count 中列多次。考虑以下数据集:
Name Game_ID Shot_Count CumSum_Shots
Player A 1 20 20
Player B 1 15 15
Player A 1 20 20
Player A 2 13 33 ## (20 + 13)
Player A 2 13 33 ## (20 + 13)
Player B 2 35 50 ## (15 + 35)
Player A 3 30 63 ## (33 + 30)
Player B 3 20 70 ## (50 + 20)
Player A 3 30 63 ## (33 + 30)
Player A 4 12 75 ## (63 + 12)
Player A 4 12 75 ## (63 + 12)
Player B 4 10 80 ## (70 + 10)
请记住,还有其他变量导致第 1 行和第 3 行等不重复。我只是想将数据集简化为相关的变量。
我尝试在 data.table 库中使用 cumsum 函数:
library(data.table)
dt[ , CumSum_Shots := cumsum(Shot_Count), by = list(dt$Name, dt$Game_ID)]
但是,这会根据游戏对 Shot_Count 行求和(即第三行 CumSum_Shots 为 40)。这段代码这样做是有道理的,但我不确定存在什么 data.table 语法以使代码考虑 dt$Game_ID 的唯一值。
【问题讨论】:
-
如果任何解决方案解决了您的问题,那么您应该accept it
标签: r data.table data-manipulation cumulative-sum