假设我有一个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
,代码就可以工作了,但是我不知道怎么做。
添加这些列的有效方法是什么?
发布于 2019-04-23 03:02:29
这里有一种方法
library(data.table)
# sample data
set.seed(123)
datapoints = data.table(replicate(3, sample(0:5, 4, rep=TRUE)))
# find if value exists
for(value in 0:5) {
datapoints[, paste("has", value, sep="") := apply(.SD, 1, function(x) any(x %in% value)), .SDcols = c("V1", "V2", "V3")]
}
datapoints
#> 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
为了更灵活,您还可以用sum(x %in% value)
替换any(x %in% value)
,以获取该值每行出现的次数。对于相同的示例
# find how many times a value exists
for(value in 0:5) {
datapoints[, paste("has", value, sep="") := apply(.SD, 1, function(x) sum(x %in% value)), .SDcols = c("V1", "V2", "V3")]
}
datapoints
#> V1 V2 V3 has0 has1 has2 has3 has4 has5
#> 1: 1 5 3 0 1 0 1 0 1
#> 2: 4 0 2 1 0 1 0 1 0
#> 3: 2 3 5 0 0 1 1 0 1
#> 4: 5 5 2 0 0 1 0 0 2
当然,如果只需要列的子集,您仍然可以使用.SDcols
。
https://stackoverflow.com/questions/55799069
复制相似问题