raf*_*ira 1 r lapply data.table
我想更新data.table中的列的值,条件是同一个表中的另外两列.
这段代码在某种程度上起作用,但我想更新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
Run Code Online (Sandbox Code Playgroud)
# 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我会这样做:
DT[, V3 := (V1 + V2) * (V1 != V2)]
# 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
Run Code Online (Sandbox Code Playgroud)
它快速而简单.