Repository navigation
Closed
Labels
bugan unexpected problem or unintended behavioran unexpected problem or unintended behaviorgrids #️⃣expanding, nesting, crossing, ...expanding, nesting, crossing, ...group 👨👨👦👦missing values 💀
Description
When running complete() on a grouped tibble and some of the variables completed on are also grouping variables, the resulting tibble is incorrect.
Here’s a reprex. First, I’ll create a simple tibble with three factors (gr1, gr2, splitgroup) and one numeric variable (x). The factor splitgroup is identical to gr1, so grouping on either variable should results in identical output. However, it doesn’t (I’ll remove splitgroup from the output just so that it doesn’t effect the ordering of the columns). There’s not even the same number of rows in the output:
library(tidyverse)
#> ── Attaching packages ───────────────────────────────────────────── tidyverse 1.2.1 ──
#> ✔ ggplot2 2.2.1 ✔ purrr 0.2.4
#> ✔ tibble 1.4.1 ✔ dplyr 0.7.4.9000
#> ✔ tidyr 0.7.2.9000 ✔ stringr 1.2.0
#> ✔ readr 1.1.1 ✔ forcats 0.2.0
#> ── Conflicts ──────────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag() masks stats::lag()
# Example data
d = tibble(
gr1 = factor(c("A", "B", "B")),
gr2 = factor(c(1, 2, 2)),
x = c(10, 20, 30),
splitgroup = gr1
)
# Complete on grouping variable
d %>%
group_by(gr1) %>%
complete(gr1, gr2) %>%
select(-splitgroup) # 10 rows
#> # A tibble: 10 x 3
#> # Groups: gr1 [2]
#> gr1 gr2 x
#> <fctr> <fctr> <dbl>
#> 1 A 1 10.0
#> 2 A 2 NA
#> 3 B 1 NA
#> 4 B 2 20.0
#> 5 B 2 30.0
#> 6 A 1 10.0
#> 7 A 2 NA
#> 8 B 1 NA
#> 9 B 2 20.0
#> 10 B 2 30.0
# Completing on non-grouping but identical variable (should give same output)
d %>%
group_by(splitgroup) %>%
complete(gr1, gr2) %>%
ungroup %>% select(-splitgroup) # 9 rows
#> # A tibble: 9 x 3
#> gr1 gr2 x
#> <fctr> <fctr> <dbl>
#> 1 A 1 10.0
#> 2 A 2 NA
#> 3 B 1 NA
#> 4 B 2 NA
#> 5 A 1 NA
#> 6 A 2 NA
#> 7 B 1 NA
#> 8 B 2 20.0
#> 9 B 2 30.0
# Alternative method to find the *expected* results
# (which are identical to the results from the
# `group_by(splitgroup)` approach)
d %>%
split(.$gr1) %>%
map_df(~complete(., gr1, gr2)) %>%
select(-splitgroup) # 9 rows
#> # A tibble: 9 x 3
#> gr1 gr2 x
#> <fctr> <fctr> <dbl>
#> 1 A 1 10.0
#> 2 A 2 NA
#> 3 B 1 NA
#> 4 B 2 NA
#> 5 A 1 NA
#> 6 A 2 NA
#> 7 B 1 NA
#> 8 B 2 20.0
#> 9 B 2 30.0Metadata
Metadata
Assignees
Labels
bugan unexpected problem or unintended behavioran unexpected problem or unintended behaviorgrids #️⃣expanding, nesting, crossing, ...expanding, nesting, crossing, ...group 👨👨👦👦missing values 💀
Activity
jnolis commentedon Jan 16, 2018
I was just coming here to post the same issue. It seems that complete ignores the grouping variables entirely. I can imagine some valid reasons for that, but if so then tidyr should output an error or at least a warning. This has caused me issues multiple times.
kendonB commentedon Jan 24, 2018
There's a natural case here to output a warning/throw an error when trying to complete a grouped tibble that is being completed based on the same groups - the operation would do nothing if complete operates on the group_df like other functions operate on group_dfs.
tbh, I can not see a use case for using
completeon a grouped df. I would advocate just ignoring the fact that it's a group_df altogether and have the behavior be identical regardless of initial grouping.huftis commentedon Jan 25, 2018
@kendonB Completing based on just the grouping variable(s) (e.g. completing A based on a tibble grouped by A) might be a strange thing do, but completing based on the grouping variables and other variables (e.g. completing A and B based on a tibble grouped by A) may very well be both sensible and useful.
huftis commentedon Jan 25, 2018
@kendonB, @hadley Hmm, I’m not sure I agree with myself anymore. I was sure I had an example where completing based on a grouping variable made sense. But I can’t find it anymore. And thinking about it, I no longer am convinced that it makes sense. So having an error message seems fine to me (I think an error is better than a warning, as the current behaviour of completing on a grouped variable is buggy).
hadley commentedon Jan 25, 2018
complete()doesn't have agrouped_dfmethod, so this is the result ofexpand.grouped_df():which TBH I'm not sure about either - the use of
do()is a warning sign. I think it should probably translate more likeI'm not sure that if that would fix the issues with
complete()too.hadley commentedon Jan 25, 2018
@huftis it's not clear to me that those commands should give the same results
To me:
(That's not what happens currently)
gvwilson commentedon Jan 4, 2019
I tripped over this one earlier today - took me a while to figure out that
completedoesn't respectgroup_by:completeto warn people about this case?hadley commentedon Jan 4, 2019
Add the grouping variables to
complete()and then regroup? I think this got stuck last time because no one reassured me that my thoughts about the desired behaviour were correct.I'd prefer to just fix it, and the timeline for getting it into CRAN is likely to be the same either way.
kendonB commentedon Jan 4, 2019
I still think that completing based on a grouping variable is an odd thing to do and should either throw an error or a warning. Responding to @hadley's year-old example:
He says:
I think that
completeshould operate on a grouped df just like other functions do. Other functions can see the grouping variables but they always only have a single value within the group. The grouping variables are always then already "complete" within the subdataframes and there would be no reason to include them, which might warrant a warning. The above then should not be equivalent.Again, I would not expect these to be equivalent. In the former, the user is asking
tidyrto complete the subdataframes defined by the grouping variablesplitgroup. The set of values forgr1andgr2need not be same across different values ofsplitgroupso every value from the big dataframe wouldn't necessarily appear in every group. The latter example askstidyrto complete the entire dataframe by all three variables, ensuring that all combinations of all three variables appear, then group by splitgroup.hadley commentedon Mar 8, 2019
@kendonB I agree with your analysis, although I think that we can just silently ignore grouping variables that are respecified in
complete(). (I think detecting them is potentially hard because bothcomplete()andgroup_by()havemutate()semantics).hadley commentedon Apr 29, 2019
Or should
hadley commentedon Apr 29, 2019
That code doesn't work, I suspect because I haven't full thought this through.
thomas-bierhance-exxcellent commentedon Jan 17, 2020
I would have expected that it behaves like this
This would basically behave more or less like applying complete on each group separately.
DavisVaughan commentedon Dec 20, 2021
I am beginning to think that
expand()should not have agrouped_dfmethod at all, and should return a bare tibble rather than one that is reconstructed fromdata.complete()would still return a grouped-df through its usage ofreconstruct_tibble().I think
expand()fundamentally creates a "new" data frame, likeexpand_grid(). It is just a small wrapper around that which also does factor expansion and makes it easier to specify where those columns come from (i.e.dataor some external vector). So it should return a bare tibble.I think the factor level expansion that occurs with
expand()is at odds with the idea of expanding within the groups that come from dplyr. This is why the original example here results in something so confusing. Here is an example:If
expand()didn't have a grouped-df method, this theoretical code would return the exact same thing (basically, thegroup_by()does nothing):With
complete(), the actual data would still be the same, but the result in the group-by cases would be grouped.If you do want to complete "within" groups, you can use the new-ish feature of
summarize()that allows you to return multi row outputs. So, you could recreate the expected original result, which is still confusing but a little easier to reason about now.This idea makes more sense with this modified example from the test suite:
hadley commentedon Dec 20, 2021
That reasoning sounds logical to me.
Add grouped-df method for `complete()`
Add grouped-df method for `complete()`
Add grouped-df method for `complete()` (#1289)
DavisVaughan commentedon Dec 21, 2021
The reasoning in #396 (comment) is sort of right, but not completely. We ended up adding a grouped-df method for
complete(), which is really all that was needed to fix the original issue. i.e. this now produces the correct results:I do think that
expand()probably never needed a grouped-df method. Onlycomplete()should have ever gotten one.complete()is a high level verb that is a combination ofexpand()withfull_join()andreplace_na(). So adding a grouped-df method is not unreasonable hereexpand()is a lower level verb. We typically don't special case grouped data frames in lower level verbs.expand()should have the invariant that it always returns unique rows. But with the grouped-df method it has the potential to return duplicate rows.Nevertheless, the grouped-df method for
expand()has been around for quite awhile, and someone probably depends on it. So we decided to keep it and only fixcomplete().