Skip to content

Allow ungroup to specify removal of grouping variable #3760

@ggrothendieck

Description

@ggrothendieck

A common case is that one constructs a grouping variable in group_by but only needs it for the duration of the group_by so afterwards one must use select to get rid of it as in the example below. It would be pleasingly symmetric if ungroup could remove the added column just as group_by adds it so

ungroup(-g)

would be the same as

ungroup %>%
select(-g)

Thus in this example taken from https://stackoverflow.com/questions/51939874/referencing-previous-column-value-as-column-is-created/51940343#51940343

test <- structure(list(i = c(0, 1, 2, 3, 4, 0, 1, 2, 3, 4), chng = c(0, 
0.031, 0.005, -0.005, 0.017, 0, 0.012, 0.003, -0.013, -0.005), 
    indx = c(1, 1.031, 1.037, 1.031, 1.048, 1, 1.012, 1.015, 
    1.002, 0.997)), class = "data.frame", row.names = c(NA, -10L
))

test %>%
  group_by(g = cumsum(i == 0)) %>%
  mutate(indx = cumprod(chng + 1)) %>%
  ungroup %>%
  select(-g)

we could write using one fewer statement, i.e. the last two lines of code above are combined into the last line below.

test %>%
  group_by(g = cumsum(i == 0)) %>%
  mutate(indx = cumprod(chng + 1)) %>%
  ungroup(-g)

Note the reduced line count and improved symmetry.

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