我想將data.table條件中的列的值更新爲同一個表中的其他兩列。在data.table中使用lapply更新值條件爲nrow
此代碼在這裏工作的方式,但我想更新我的DT中的值,而不是返回一個DT列表。
重複的例子:
library(data.table)
library(gtools)
# Create Data Table
DT <- as.data.table(combinations(3,2,1:3,repeats=TRUE))
DT[, V3 := 9999 ]
DT
> V1 V2 V3
>1: 1 1 9999
>2: 1 2 9999
>3: 1 3 9999
>4: 2 2 9999
>5: 2 3 9999
>6: 3 3 9999
我的代碼:
# create function
stationary <- function(i) {DT[i, V3 := if (V1==V2) 0 else V1+V2 ]}
i <- 1:nrow(DT)
DT <- lapply(i, stationary) # This returns a list of identical data tables
我想要的結果:
DT
> V1 V2 V3
>1: 1 1 0
>2: 1 2 3
>3: 1 3 4
>4: 2 2 0
>5: 2 3 5
>6: 3 3 0
迭代所有觀察值總是很慢。你至少可以使用'ifelse'。 – Roland
我最初考慮用'if else'循環。我仍然對我的問題採取最好的方法。我可能不得不發佈另一個問題。 –
我寫了'ifelse',它是一個矢量化函數,而不是'if else'。 – Roland