R 如何检查data.table的各个行中的值是否相同

R 如何检查data.table的各个行中的值是否相同,r,data.table,rowwise,R,Data.table,Rowwise,假设我有以下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 我希望避免使用重复的函数,并希望坚持使用相同的或类似的函数,即使这意味着要遍历每行中的项目。uniqueN可以按行分组并创建逻辑表达式(==1) -输出 dt # a b c d #1: 1 1 1 identical #2: 2 2 1 not

假设我有以下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

我希望避免使用重复的
函数,并希望坚持使用相同的
或类似的函数,即使这意味着要遍历每行中的项目。

uniqueN
可以按行分组并创建逻辑表达式(
==1

-输出

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

《复制品》有什么问题?@MichaelChirico我认为《复制品》
无法检测课堂上的差异,而《完全相同》
则可以?
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