【问题标题】:Dynamic and Conditional Column Updating in data.tabledata.table 中的动态和条件列更新
【发布时间】:2016-10-13 20:56:50
【问题描述】:

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

【问题讨论】:

    标签: r data.table dplyr zoo


    【解决方案1】:

    您可以在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
    

    【讨论】:

    • 感谢您的回答!这是一个很好的解决方案。
    猜你喜欢
    • 2019-07-24
    • 1970-01-01
    • 2022-07-27
    • 2012-07-29
    • 1970-01-01
    • 2018-06-01
    • 2015-04-08
    • 1970-01-01
    相关资源
    最近更新 更多