假设我有一个data.table
,其中C列保存N个可能值中的离散值:
set.seed(123)
datapoints = data.table(replicate(3, sample(0:5, 4, rep=TRUE)))
print(datapoints)
V1 V2 V3
1: 1 5 3
2: 4 0 2
3: 2 3 5
4: 5 5 2
(这里是C=3和N=5)
我想添加N列,如果C列之一包含第N个值,则每列包含TRUE
,否则为FALSE
:
V1 V2 V3 has0 has1 has2 has3 has4 has5
1: 1 5 3 FALSE TRUE FALSE TRUE FALSE TRUE
2: 4 0 2 TRUE FALSE TRUE FALSE TRUE FALSE
3: 2 3 5 FALSE FALSE TRUE TRUE FALSE TRUE
4: 5 5 2 FALSE FALSE TRUE FALSE FALSE TRUE
我已经尝试过了:
for (value in 0:5) {
datapoints <- datapoints[, (paste("has", value, sep="")) := (value %in% .SD), .SDcols = c("V1", "V2", "V3")]
}
列已添加,但填充了FALSE
V1 V2 V3 has0 has1 has2 has3 has4 has5
1: 1 5 3 FALSE FALSE FALSE FALSE FALSE FALSE
2: 4 0 2 FALSE FALSE FALSE FALSE FALSE FALSE
3: 2 3 5 FALSE FALSE FALSE FALSE FALSE FALSE
4: 5 5 2 FALSE FALSE FALSE FALSE FALSE FALSE
在我看来,如果我用对当前行(而不是整个表)的引用替换.SD
,代码就可以工作了,但是我不知道怎么做。
添加这些列的有效方法是什么?
https://stackoverflow.com/questions/55799069
复制相似问题