要跟踪现金流的我有许多相互关联的列在data.table:相关列data.table
- “Amount_spent”始终是“平衡”的5%。
- “收入”是“Amount_spent”*“价格”
- “余额”是“收入”(从100.00开始)的累计总和。
- 交易只发生在“天”“一”
我很努力的同时计算出这些相互关联的列。 例子,因为我想:
library(data.table)
Day <- c("a", "c", "b", "a", "b", "a", "b", "c", "a", "a")
Price <- c(0.6, 0.4, 0.9, -0.3, 0.8, 0.2, 0.3, 0.9, 0.9, -0.7)
Balance <- c(100.00, 103.00, 103.00, 103.00, 101.46, 101.46, 102.47, 102.47, 102.47, 107.08)
Amount_spent <- c(5.00, 0.00, 0.00, 5.15, 0.00, 5.07, 0.00, 0.00, 5.12, 5.35)
Revenue <- c(3.00, 0.00, 0.00, -1.55, 0.00, 1.01, 0.00, 0.00, 4.61, -3.75)
DT <- data.table(Day, Price, Balance, Amount_spent, Revenue)
DT
这是迄今为止我尝试:
# set initial balance
Balance2 <- 100.00
Day2 <- c("a", "c", "b", "a", "b", "a", "b", "c", "a", "a")
Price2 <- c(0.6, 0.4, 0.9, -0.3, 0.8, 0.2, 0.3, 0.9, 0.9, -0.7)
my.try <- data.table(Day2, Price2)
my.try[, Balance2 := cumsum(Revenue2)]
my.try[ Day2 == "a", Amount_spent2 := Balance2 * 0.05 ]
my.try[is.na(Amount_spent2), Amount_spent2 := 0]
my.try[, Revenue2 := Price2 * Amount_spent2 ]
my.try
正如你将看到它失败的“REVENUE2”列此错误消息Error in eval(expr, envir, enclos) : object 'Revenue2' not found
是尚未建立。
谢谢
为什么不使用'my.try [is.na(Amount_spent2),Amount_spent2:= 0]'而不是使用'<-'对data.table列(坏习惯),同时放弃'na.zero'函数在所有。 – jangorecki
谢谢,我编辑了我的代码 – user3740289
@jangorecki感谢您的建议。有关如何同时计算列的任何想法? – user3740289