Skip to content

complete doesn't work well with grouped data frames. #966

@cimentadaj

Description

@cimentadaj

I just spent a few minutes figuring out why complete was generating all combination of values. This was happening because the data frame was grouped. Perhaps it would be useful to others to document this in the details section of complete.

library(dplyr, warn.conflicts = FALSE)
library(tidyr)
df <- tibble(
  group = c(1:2, 1),
  item_id = c(1:2, 2),
  item_name = c("a", "b", "b"),
  value1 = 1:3,
  value2 = 4:6
)

# Expected
df %>% complete(group, item_id, item_name)
#> # A tibble: 8 x 5
#>   group item_id item_name value1 value2
#>   <dbl>   <dbl> <chr>      <int>  <int>
#> 1     1       1 a              1      4
#> 2     1       1 b             NA     NA
#> 3     1       2 a             NA     NA
#> 4     1       2 b              3      6
#> 5     2       1 a             NA     NA
#> 6     2       1 b             NA     NA
#> 7     2       2 a             NA     NA
#> 8     2       2 b              2      5

# Not expected
df %>%
  group_by(group, item_id, item_name) %>%
  complete(group, item_id, item_name)
#> # A tibble: 3 x 5
#> # Groups:   group, item_id, item_name [3]
#>   group item_id item_name value1 value2
#>   <dbl>   <dbl> <chr>      <int>  <int>
#> 1     1       1 a              1      4
#> 2     1       2 b              3      6
#> 3     2       2 b              2      5

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions