【问题标题】:R count number of distincts not consistentR计数不同的数量不一致
【发布时间】:2018-07-14 16:59:52
【问题描述】:
library(dplyr)

distinct(mtcars, mpg) 显示 mtcars 中唯一出现的 mpg 类。

n_distinct(mtcars, mpg) 对它们进行计数并显示正确的计数32

distinct(mtcars, cyl) 显示 mtcars 中汽缸类的唯一出现次数。

n_distinct(mtcars, cyl) 产生错误。为什么它不像上面的 mpg 示例那样工作?我收到了这个不正确的错误...对象 cyl 在 mtcars 数据框中,我向你保证。

Error in n_distinct_multi(list(...), na.rm) : object 'cyl' not found

【问题讨论】:

  • 你一定对mpg做过什么。如果你开始一个新的会话并运行n_distinct(mtcars, mpg),你也会得到一个错误。试试ls(),看看你是否创建了一个名为mpg的对象。
  • ggplot2 中有一个mpg 对象,您可能已经加载了它。

标签: r


【解决方案1】:

dplyr::n_distinct() 函数不是mutate()filter() 等表动词。它的... 参数应该是“值向量”(根据官方文档)。

所以当你说dplyr::n_distinct(mtcars, mpg)时,真正发生了什么 是正在计算第一个参数mtcars 的唯一值。

因为它有 32 个不同的行,所以值为 32。在最后一个示例中,您 提供,cyl 无法识别,因为没有名为 cyl 的对象——mpg 被识别的原因 mpg 指的是 数据集ggplot2::mpgmtcars的同名列!

要明白我的意思,运行以下命令:

dplyr::n_distinct(mtcars)                # 32 
dplyr::n_distinct(ggplot2::mpg)          # 225 
dplyr::n_distinct(mtcars, mpg)           # 32 
dplyr::n_distinct(mtcars, ggplot2::mpg)  # 32 

如果要统计mtcars$cylmtcars$mpg中唯一值的个数, 然后只需使用:

dplyr::n_distinct(mtcars$cyl) # 3 
dplyr::n_distinct(mtcars$mpg) # 25 

一个棘手的问题!

【讨论】:

    【解决方案2】:

    您对 n_distinct(mtcars, mpg) 的调用未返回正确的值,即 25。相反,此行为您提供整个表 mtcars 中的唯一行数,根据 @ 的输出为 32 987654323@.

    您要调用的是返回 25 的 n_distinct(mtcars$mpg),或者类似地在 cyl 列上您要说的是 n_distinct(mtcars$cyl)n_distinct(mtcars[["cyl"]])(等效)。

    > distinct(mtcars, cyl)
      cyl
    1   6
    2   4
    3   8
    > n_distinct(mtcars$cyl)
    [1] 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 2015-07-16
      • 2019-08-11
      • 2019-09-19
      • 1970-01-01
      • 2021-11-10
      相关资源
      最近更新 更多