R基于两个变量的累积和

时间:2016-11-06 17:57:13

标签: r data.table dplyr cumsum

这是我的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]

1 个答案:

答案 0 :(得分:3)

我们可以执行双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