【问题标题】:r Data Table gives different result when using Withr 使用 With 时数据表给出不同的结果
【发布时间】:2020-03-03 11:56:55
【问题描述】:

我想知道数据表在直接指向列或通过字符指向列时给出不同结果是否有逻辑原因。

例如

library(data.table)

iris_dt <- data.table(iris)

iris_dt[, NROW(unique(Species))]

# 3

col <- 'Species'

iris_dt[, NROW(unique(col)), with = FALSE]

# Prints the Sepal Length, which does not make sense to me

代码的第二部分发生了什么?

【问题讨论】:

  • unique('Species') 带给你什么?
  • 好的,那我明白为什么它返回第一列了。但为什么它不返回“3”?因为我只是想通过字符向量而不是直接在第一个语句中调用列。
  • 它返回你的角色对象"Species"的长度,即1。你想要的大概是iris_dt[, NROW(unique(iris[col])), with=FALSE]

标签: r data.table


【解决方案1】:

在代码的第二部分中,您选择的是 data.table 的第一列。

# Equivalent too
iris_dt[, 1, with = FALSE]
# Because
NROW('Species') == 1 # TRUE

# Also 
unique('Species') == 'Species' # TRUE

'Species' 只是一个长度为 1 的(字符)向量,NROW() 返回它的长度。

我认为您正在寻找的是:

iris_dt[, uniqueN(get(col))] # 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2017-05-21
    相关资源
    最近更新 更多