【问题标题】:Why does dplyr::distinct behave like this for grouped data frames为什么 dplyr::distinct 对分组数据帧表现得像这样
【发布时间】:2015-09-24 09:45:50
【问题描述】:

我的问题涉及来自dplyr 的distinct 函数。

首先,设置数据:

set.seed(0)

df <- data.frame(
    x = sample(10, 100, rep = TRUE),
    y = sample(10, 100, rep = TRUE)
)

考虑distinct的以下两种用法。

df %>%
    group_by(x) %>%
    distinct()

df %>%
    group_by(x) %>%
    distinct(y)

第一个产生与第二个不同的结果。据我所知,第一组操作找到“x 的所有不同值,并返回y 的第一个值”,而第二组操作找到“对于x 的每个值,找到所有不同的值y"。

为什么会这样

df %>%
    distinct(x, y)

df %>% distinct()

产生同样的结果?

编辑:看起来这是一个已知的错误:https://github.com/hadley/dplyr/issues/1110

【问题讨论】:

  • 仅供参考,这似乎已得到修复。所有 4 个示例对我来说都返回了相同的结果,这正是我所期望的。

标签: r dplyr


【解决方案1】:

据我所知,答案是distinct 在确定独特性时考虑对列进行分组,在我看来这与dplyr 的其余部分的工作方式不一致。

因此:

df %>%
group_by(x) %>%
distinct()

按x 分组,查找x(!) 中不同的值。这似乎是一个错误。

但是:

df %>%
group_by(x) %>%
distinct(y)

按x 分组,在给定x 的情况下查找y 中不同的值。这相当于以下任何一种情况:

df %>%
distinct(x, y)

df %>% distinct()

两者都在 x 和 y 中找到不同的值。

关键信息似乎是:不要使用分组和distinct。只需在distinct 中使用相关的列名作为参数。

【讨论】:

  • 所以,这是一个错误,对吧?因为它与 group_by 的帮助文件不兼容:The group_by function takes an existing tbl and converts it into a grouped tbl where operations are performed "by group".
  • 我想是的。在您指出之前,我没有注意到这种行为,而且它似乎与我预期的 group_by() 行为不一致。
  • 我认为您对第一个操作df %&gt;% group_by(x) %&gt;% distinct() 的描述有误。它应该是“在x 中查找不同的值”。
  • 是的,我刚刚编辑了答案。最好不要将group_by() 和distinct() 混合使用。
猜你喜欢
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
相关资源
最近更新 更多