为什么 complete() 在我的数据中创建重复的行?

Joe*_*Joe 6 r tidyr

当我使用 complete() 函数填充数据中没有案例的行时,我发现它也创建了许多重复的行。这些可以使用 unique() 函数删除,但我想了解如何避免首先生成所有这些额外的行。

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)
Run Code Online (Sandbox Code Playgroud)

alk*_*989 8

这在@aosmith 的评论中得到了回答。

重复项来自分组数据。使用取消分组ungroup解决了这个问题:

temp <- 
  mtcars %>% 
  group_by(vs, cyl) %>% 
  count() %>% 
  ungroup() %>%
  complete(vs = c(0, 1), cyl = c(4, 6, 8), fill = list(n = 0)) 
Run Code Online (Sandbox Code Playgroud)