本文介绍了为什么 complete() 在我的数据中创建重复的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用 complete() 函数填充数据中没有案例的行时,我发现它也创建了许多重复的行.这些可以使用 unique() 函数删除,但我想了解如何避免首先生成所有这些额外的行.
When I use the complete() function to fill in rows in my data that have no cases I find it is creating many duplicate rows as well. These can be removed with the unique() function, but I want to understand how I can avoid generating all these extra rows in the first place.
library(dplyr)
library(tidyr)
# An incomplete table
mtcars %>%
group_by(vs, cyl) %>%
count()
# complete() creates a table with many duplicate rows
temp <-
mtcars %>%
group_by(vs, cyl) %>%
count() %>%
complete(vs = c(0, 1), cyl = c(4, 6, 8), fill = list(n = 0))
unique(temp)
推荐答案
@aosmith 在评论中回答了这个问题.
This is answered in a comment by @aosmith.
重复项来自分组数据.使用 ungroup
取消分组解决了这个问题:
The duplicates come from the grouped data. Ungrouping using ungroup
solves the issue:
temp <-
mtcars %>%
group_by(vs, cyl) %>%
count() %>%
ungroup() %>%
complete(vs = c(0, 1), cyl = c(4, 6, 8), fill = list(n = 0))
这篇关于为什么 complete() 在我的数据中创建重复的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!