CumSum 基于组只计算一次值

kla*_*123 2 r data-manipulation cumulative-sum data.table

我目前正在尝试创建一个累积总和列,它将根据 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)
Run Code Online (Sandbox Code Playgroud)

请记住,还有其他变量可以使第 1 行和第 3 行等不重复。我只是想将数据集简化为相关的变量。

我尝试在 data.table 库中使用 cumsum 函数:

library(data.table)
dt[ , CumSum_Shots := cumsum(Shot_Count), by = list(dt$Name, dt$Game_ID)]
Run Code Online (Sandbox Code Playgroud)

但是,这会根据游戏对 Shot_Count 行进行求和(即 CumSum_Shots 第三行将是 40)。这段代码这样做是有道理的,但我不确定存在什么 data.table 语法以使代码考虑 dt$Game_ID 的唯一值。

edd*_*ddi 5

唯一,计算,然后合并回来:

dt[unique(dt, by = c('Name', 'Game_ID', 'Shot_Count'))
       [, Cum_Shots := cumsum(Shot_Count), by = Name]
   , on = .(Name, Game_ID), Cum_Shots := Cum_Shots]
Run Code Online (Sandbox Code Playgroud)

R 是一种肮脏的语言。