Reputation: 121
In dplyr
with R, if I've grouped by multiple variables can I then ungroup by a subset of those with ungroup
? As far as I can tell, ungroup
ignores any arguments provided and always ungroups everything.
Example:
mtcars %>%
group_by(cyl, vs, am) %>%
# this removes 'am' but grouping by 'cyl' and 'vs' remain
summarize(n = n()) %>%
ungroup(vs) # I want this to work but it ungroups everything, not just 'vs'
Is there a way to remove the grouping by vs
while keeping the grouping by cyl
? I can accomplish this via
mtcars %>%
group_by(cyl, vs, am) %>%
summarize(n = n()) %>%
ungroup() %>%
group_by(cyl)
but I feel like there has to be a better way than removing both groupings and re-adding just the cyl
grouping.
I'm using the summarize
in my examples because that's my particular context, but this behavior seems to be evident even in something as minimal as this:
mtcars %>%
group_by(cyl, vs) %>%
ungroup(vs) # ungroups everything, not just 'vs'
Update: Thanks everyone for the great suggestions and comments. I just tried this and it works with no fuss due to add=FALSE
in group_by
, and it's as clean as what I was hoping ungroup
could do:
mtcars %>%
group_by(cyl, vs, am) %>%
summarize(n = n()) %>%
group_by(cyl)
Thanks to @camille and @julius-vainora I know that ungroup
by itself cannot do this, so I'll have to do grouping rather than ungrouping. @RyanD's suggestions were also very helpful.
Upvotes: 2
Views: 1979
Reputation: 405
Answering this question based on present dplyr documentation: https://dplyr.tidyverse.org/articles/grouping.html
"You can also choose to selectively ungroup by listing the variables you want to remove:"
by_sex_gender %>%
ungroup(sex) %>%
tally()
Upvotes: 2