简体   繁体   English

根据data.table中其他列的计算值来计算一列的滚动总和

[英]calculate rolling sum in a column based on calculated values in other columns in data.table

I am trying to calculate values in a column from calculated values from another column. 我正在尝试根据另一列的计算值来计算一列中的值。

DT <- data.table(X = c("a","a","a", "b","b","b", "c","c","c"),
                 Y = rep(c(1,2,3),3),
                 z1 = c(10, 11,12),
                 z2 = c(1,2,3))

Here in DT, I want to calculate a new column Z which is sum of z1 and z2 for first row for each X. Next row calculation should be done from the previously calculated Z + current row z2 for all rows of "a". 在DT中,我要计算一个新列Z,它是每个X的第一行的z1和z2之和。下一行的计算应从先前计算的Z +当前行z2的所有“ a”行进行。 Similarly for "b", "c". 对于“ b”,“ c”类似。
I did try with "for" loops but was not successful. 我确实尝试过“ for”循环,但未成功。 The end result looks like this. 最终结果如下所示。

X   Y   z1  z2  Z
a   1   10  1   11
a   2   11  1   12
a   3   12  1   13
b   1   10  2   12
b   2   11  2   14
b   3   12  2   16
c   1   10  3   13
c   2   11  3   16
c   3   12  3   19

您可以使用

DT[, Z := cumsum(z2) + z1[1], by= X]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM