在条件为 nrow 的 data.table 中使用 lapply 更新值
Update values using lapply in a data.table conditional to nrow
我想将 data.table 条件中一列的值更新为同一 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
我的代码:
# 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
我会这样做:
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
它又快又简单。
您可以使用链接:
library(data.table)
library(gtools) # combinations()
DT <- as.data.table(combinations(3,2,1:3,repeats=TRUE))
DT[, V3 := 9999 ]
DT[V1==V2, V3 := 0
][V1!=V2, V3 := as.numeric(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
如果坚持使用整数,可以避免调用 as.numeric
,因此 V3 := 9999L
和 V3 := 0L
。
我想将 data.table 条件中一列的值更新为同一 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
我的代码:
# 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
我会这样做:
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
它又快又简单。
您可以使用链接:
library(data.table)
library(gtools) # combinations()
DT <- as.data.table(combinations(3,2,1:3,repeats=TRUE))
DT[, V3 := 9999 ]
DT[V1==V2, V3 := 0
][V1!=V2, V3 := as.numeric(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
如果坚持使用整数,可以避免调用 as.numeric
,因此 V3 := 9999L
和 V3 := 0L
。