R基于两个变量的累积和

R Cumulative sum based on two variables

这就是我的 data.table 的样子。最后一列 NewShares 是我想要的列。

library(data.table)
dt <- fread('
   Client   Level   NumShares   Interest  NewShares 
    A          0     10          0         10
    A          0     0           0         10
    A          1     0          .1         11
    A          0     9           0         20
    A          1     0          .2         24')

我想要累积的 NumShares,同时考虑有兴趣购买的 NewShares。所以从第 1 行开始,累计份额为 10。从第 3 行开始,Level==1,所以我必须添加利息。它将是 10+(10*.1)=11。截至第 4 行,累计份额为 11+9 =20。截至最后一行,Level==1,因此新股为 20+(20*.2) = 24

我试过了:

dt[,NewShares:= NumShares* cumprod(1+ NumShares*Interest),by=Client]

我们可以做双 cumsum 然后用 ceiling

包裹起来
dt[, NewSharesN := ceiling(cumsum(cumsum(NumShares)*Interest + NumShares)) , by = Client]
dt
#   Client Level NumShares Interest NewShares NewSharesN
#1:      A     0        10      0.0        10         10
#2:      A     0         0      0.0        10         10
#3:      A     1         0      0.1        11         11
#4:      A     0         9      0.0        20         20
#5:      A     1         0      0.2        24         24