要跟蹤現金流的我有許多相互關聯的列在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