【问题标题】:How to check if values in individiual rows of a data.table are identical如何检查data.table的各个行中的值是否相同
【发布时间】:2021-01-01 00:05:46
【问题描述】:

假设我有以下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 或类似函数,即使这意味着遍历每一行中的项目。

【问题讨论】:

  • 重复有什么问题?
  • @MichaelChirico 我认为duplicated 无法检测到班级差异,而​​identical 可以?

标签: r data.table rowwise


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是另一个使用vardata.table 选项

    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
    

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 2018-01-28
      • 1970-01-01
      • 2020-12-01
      • 2015-10-16
      • 2023-03-22
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多