R Data.Table 创建一个带条件的变量

R Data.Table create a variable with a condition

我需要在下面的数据集中创建一个新变量:

A  X
a  1
b  2
c  3
d  4
e  5
f  6
g  7
h  8
i  9
j 10

如果 X 等于 2、5、7 或 9,则 newvar 的值为 1。否则,newvar 应为 0。

代码:

dt1 <- data.table(A = letters[1:10], X = 1:10, key = "X")
numberlist <- list(2,5,7,9)

我已经根据 post here 尝试了以下方法:

dt1[, newvar:=.SD, .SDcols = 0][%in% numberlist, newvar:=.SD, .SDcols = 1]
dt1[, newvar:=.SD, .SDcols = 0][X %in% numberlist, newvar:=.SD, .SDcols = 1]

dt1[, newvar:=.SD, .SDcols = 0] 表示 "assign value of 0 to newvar as default option. The second bracket [%in% numberlist, newvar:=.SD, .SDcols = 1] means " 如果键 (X) 包含在数字列表中,则将 newvar 值设置为 1。

知道为什么它不起作用吗?

尝试

dt1[, newvar:=(X %in% c(2,5,7,9))+0L][]
#     A  X newvar
# 1: a  1      0
# 2: b  2      1
# 3: c  3      0
# 4: d  4      0
# 5: e  5      1
# 6: f  6      0
# 7: g  7      1
# 8: h  8      0
# 9: i  9      1
#10: j 10      0

或者如果我们已经将匹配元素存储在一个向量中

numberlist <- c(2,5,7,9)
dt1[, newvar:=as.numeric(X %in% numberlist)] 

as.numeric 是将逻辑向量强制为 0/1 值的另一种选择。