问题描述
我需要在下面的数据集中创建一个新变量:
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
如果 X $ c,
newvar
的值为1 $ c>等于2,5,7或9。否则, newvar
应该为0。
The newvar
will have value 1 if X
equals 2,5,7 or 9. Otherwise, newvar
should be 0.
代码:
dt1 <- data.table(A = letters[1:10], X = 1:10, key = "X")
numberlist <- list(2,5,7,9)
I根据帖子:
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]
的意思是分配值e的0到newvar作为默认选项。第二括号 [%in%数字列表,newvar:=。SD,.SDcols = 1]
表示如果数字列表中包含键(X),请设置 newvar
的值为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.
知道为什么它不起作用吗?
Any idea why it is not working?
推荐答案
尝试
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
是将逻辑矢量强制为 0/1
值的另一种选择。
as.numeric
is another option to coerce the logical vector to 0/1
values.
这篇关于R Data.Table创建一个带有条件的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!