data.table 中的动态和条件列更新

Dynamic and Conditional Column Updating in data.table

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

 StartingAmount<-10
 library(data.table)    
 dt <- fread('
                 Level   Interest  New_Amount
                    0      .5        10
                    1      .5        15
                    0      .5        15
                    0      .3        15
                    1      .2        18
                    0      .4        18
                    1      .5        27
        ')

假设我从 10 美元开始。对于 Level = 1 的每一行,我想在添加利息后计算我的新金额。所以对于 Level =1 的第二行,我的 New_Amount 是 10+(10*.5) =15。在 Level=1 的第 5 行,我的 New_Amount 是 15+(15*.2)=18。我将忽略 Level=0 的行,只进行最后一次观察。

这是我的尝试:

dt[, NewAmount:= ifelse(Level==1,StartingAmount+StartingAmount*Interest,0)]
  dt[, NewAmount:= ifelse(Level==1, New_Amount + New_Amount*Interest , NA)]

您可以在 Interest 列上使用 cumprod,您可以将其与 Level 列相乘,以确定是否应向前一列添加额外利息:

library(data.table)
dt[, New_Amount := StartingAmount * cumprod(1 + Level * Interest)][]

#   Level Interest New_Amount
#1:     0      0.5         10
#2:     1      0.5         15
#3:     0      0.5         15
#4:     0      0.3         15
#5:     1      0.2         18
#6:     0      0.4         18
#7:     1      0.5         27