## 添加一个data.table列，告诉C其他C列之一是否包含某个值内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (14)

``````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）

``````   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")]
}
``````

``````   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
``````

### 1 个回答

``````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
``````

``````# 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
``````