I need to create a new variable in the dataset below:
我需要在数据集中创建一个新的变量:
A X
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
The newvar
will have value 1 if X
equals 2,5,7 or 9. Otherwise, newvar
should be 0.
如果X等于2、5、7或9,则新var的值为1。否则,newvar应该是0。
Code:
代码:
dt1 <- data.table(A = letters[1:10], X = 1:10, key = "X")
numberlist <- list(2,5,7,9)
I have tried the following based on a 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]
means "assign value of 0 to newvar as default option. The second bracket [%in% numberlist, newvar:=.SD, .SDcols = 1]
means "if the key (X) is included in the numberlist, set the newvar
value to 1.
dt₁[newvar:=。SD, . sdcols = 0]表示“将0赋给newvar为默认选项”。第二个括号[%在% numberlist中,newvar:=]。SD, . sdcols = 1]表示“如果数字列表中包含键(X),则将newvar值设置为1”。
Any idea why it is not working?
你知道它为什么不工作吗?
1 个解决方案
#1
3
Try
试一试
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
Or if we already have the matching elements stored in a a vector
或者如果我们已经将匹配元素存储在向量中
numberlist <- c(2,5,7,9)
dt1[, newvar:=as.numeric(X %in% numberlist)]
as.numeric
is another option to coerce the logical vector to 0/1
values.
作为。数字是将逻辑向量强制为0/1值的另一个选项。
#1
3
Try
试一试
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
Or if we already have the matching elements stored in a a vector
或者如果我们已经将匹配元素存储在向量中
numberlist <- c(2,5,7,9)
dt1[, newvar:=as.numeric(X %in% numberlist)]
as.numeric
is another option to coerce the logical vector to 0/1
values.
作为。数字是将逻辑向量强制为0/1值的另一个选项。