我的问题涉及来自dplyr的dplyr函数。
首先,设置数据:
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()产生同样的结果?
编辑:看起来这是一个已知的bug:https://github.com/hadley/dplyr/issues/1110
发布于 2015-07-07 04:08:37
据我所知,答案是distinct在确定区分性时考虑分组列,在我看来,这与dplyr的其他部分的工作方式不一致。
因此:
df %>%
group_by(x) %>%
distinct()按x分组,查找x(!)中不同的值。这好像是个虫子。
然而:
df %>%
group_by(x) %>%
distinct(y)按x分组,查找在y给定的x中不同的值。这相当于上述两种情况中的一种:
df %>%
distinct(x, y)
df %>% distinct()两者都在x和y中找到不同的值。
带回家的信息似乎是:不要使用分组和distinct。只需在distinct中使用相关的列名作为参数。
https://stackoverflow.com/questions/31259518
复制相似问题