假设我有以下数据表:
dt <- data.table(a = 1:2, b = 1:2, c = c(1, 1))
# dt
# a b c
# 1: 1 1 1
# 2: 2 2 1
创建第四列 d
的最快方法是什么,表示每行中预先存在的值都相同,以便生成的 data.table 如下所示?
# dt
# a b c d
# 1: 1 1 1 identical
# 2: 2 2 1 not_identical
我想避免使用 duplicated
函数并坚持使用 identical
或类似函数,即使这意味着遍历每一行中的项目。
最佳答案
uniqueN
可以按行分组并创建逻辑表达式 (== 1
)
library(data.table)
dt[, d := c("not_identical", "identical")[(uniqueN(unlist(.SD)) == 1) +
1], 1:nrow(dt)]
-输出
dt
# a b c d
#1: 1 1 1 identical
#2: 2 2 1 not_identical
或者另一种有效的方法可能是与第一列进行比较,并使用 rowSums
dt[, d := c("identical", "not_identical")[1 + rowSums(.SD[[1]] != .SD) > 0 ] ]
关于r - 如何检查 data.table 各行中的值是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65526420/