r - 如何检查 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 ] ]

https://stackoverflow.com/questions/65526420/

相关文章:

powershell - 在 switch 语句中分配变量

firebase - Flutter Firestore 离线数据库

android-studio - flutter SDK 不完整

reactjs - 接口(interface)命名约定(接口(interface)名称与组件名称冲突

c++ - fatal error LNK2019 C++,Unreal Engine Build

python - 根据所选列过滤重复的行并与 Pandas 中的另一个数据框进行比较

git - 如何为 gerrit 事件配置 Gerrit Webhooks

python - 功能测试没有按预期进行(AoC 第 4 天的一部分)

javascript - JavaScript 中的常量数组

c++ - 在模板参数中,哪些规则允许编译器推断数组的项数?