我创建了以下可重现的示例:
library(data.table)
Col_1 <- 0.05
Col_2 <- c( "B", "A", "C", "B", "C", "A", "C", "B", "B", "A" )
Col_3 <- 1000
Col_4 <- ""
data <- data.frame( Col_1, Col_2, Col_3, Col_4 )
mydata.table <- as.data.table( data )[ , list( Col_1, Col_2, Col_3, Col_4 ) ]
Col1 <- "Col_1"; Col2 <- "Col_2"; Col3 <- "Col_3"; Col4 <- "Col_4"
mydata.table[, (Col4) := ifelse( get( Col2 ) == "A" , get( Col1 ) * get( Col3 ), "0" ) ]
mydata.table[ , (Col3) := cumsum( c( 1000, head( Col4, -1 )))]
我的问题是 Col3 没有正确计算 cumsum 并且在 1000 处保持静态。我已经根据本网站上的其他答案改编了我的代码,但需要一些帮助。我希望 Col3 从 1000 开始,然后累积添加 Col4(滞后上一行)。
我希望输出显示以下内容:
Col_1 <- 0.05
Col_2 <- c( "B", "A", "C", "B", "C", "A", "C", "B", "B", "A")
Col_3 <- c( 1000.0, 1000.0, 1050.0, 1050.0, 1050.0, 1050.0, 1102.5, 1102.5, 1102.5, 1102.5 )
Col_4 <- c( 0, 50.0, 0, 0, 0, 52.5, 0, 0, 0, 55.1 )
good_data <- data.frame( Col_1, Col_2, Col_3, Col_4 )
gooddata.table <- as.data.table( good_data )[ , list( Col_1, Col_2, Col_3, Col_4 )]
这是否需要循环计算,因为每一列都依赖于另一列的结果?谢谢你。
由于@Frank 的回答,根据下面的评论更新示例并包括新代码:
library(data.table)
Col_1 <- 0.05
Col_2 <- c( "B", "A", "C", "B", "C", "A", "C", "B", "B", "A" )
Col_3 <- 1000
Col_4 <- 0
mydata.table <- data.table(Col_1, Col_2, Col_3, Col_4)
Col1 <- "Col_1"; Col2 <- "Col_2"; Col3 <- "Col_3"; Col4 <- "Col_4"
mydata.table[, (Col3) := Col_3*cumprod(1+Col_1*shift(Col_2=="A", type="lag", fill=FALSE))]
mydata.table[, (Col4) := ifelse( get( Col2 ) == "A" , get( Col1 ) * get( Col3 ), "0" ) ]