如何检查 data.table 的各行中的值是否相同
How to check if values in individiual rows of a data.table are identical
假设我有以下 data.table:
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 ] ]
这是另一个 data.table
选项,使用 var
dt[, d := ifelse(var(unlist(.SD)) == 0, "identical", "non_identical"), seq(nrow(dt))]
这给出了
> dt
a b c d
1: 1 1 1 identical
2: 2 2 1 non_identical
假设我有以下 data.table:
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 ] ]
这是另一个 data.table
选项,使用 var
dt[, d := ifelse(var(unlist(.SD)) == 0, "identical", "non_identical"), seq(nrow(dt))]
这给出了
> dt
a b c d
1: 1 1 1 identical
2: 2 2 1 non_identical