[英]R data.table cumulative sum function
I have created the following reproducible example: 我创建了以下可重现的示例:
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 )))]
My problem is that Col3 is not calculating the cumsum correctly and remains static at 1000. I have adapted my code from other answers on this site but need a little help please. 我的问题是Col3不能正确计算总和,并且在1000时保持静态。我已经根据本网站上的其他答案改编了我的代码,但请提供一些帮助。 I would like Col3 to start at 1000 then cumulatively add Col4 (lagging by one row above).
我希望Col3从1000开始,然后累计添加Col4(在上面滞后一行)。
I would like the output to show the following: 我希望输出显示以下内容:
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 )]
Would this need to be calculated in a loop as each column relies on the result of another? 由于每一列都依赖于另一列的结果,是否需要循环计算? Thank you.
谢谢。
UPDATE to example based on comments below and including new code thanks to @Frank 's answer: 根据下面的注释更新示例,并感谢@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" ) ]
To get your desired output, try skipping creation of the intermediate object Col_4
and just doing 为了获得所需的输出,请尝试跳过中间对象
Col_4
创建,然后执行
mydata.table[, Col_3*cumprod(1 + Col_1*shift(Col_2 == "A", type = "lag", fill=FALSE))]
To understand how this works, try ?cumprod
and ?shift
. 要了解其工作原理,请尝试使用
?cumprod
和?shift
。 You can also run it in pieces, eg, 您也可以分段运行它,例如
mydata.table[, shift(Col_2 == "A", type = "lag", fill = FALSE)]
(I'm ignoring your issues with get
mentioned in comments; as well as your overwriting of Col_3
.) (我忽略了您在注释中
get
提及的问题;以及您对Col_3
的覆盖。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.