【问题标题】:R Cumulative sum based on two variablesR 基于两个变量的累积和
【发布时间】: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


【解决方案1】:

我们可以做双重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

【讨论】: