【发布时间】:2025-12-30 15:00:17
【问题描述】:
这就是我的 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。所以第一行,累计10股。第三行,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]
【问题讨论】:
-
或许
dt[, NewSharesN := ceiling(cumsum(cumsum(NumShares)*Interest + NumShares)) , Client]
标签: r data.table dplyr cumsum