[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.