Description Usage Arguments See Also Examples
Occasionally it is useful to ungroup a data frame before applying a
calculation that would otherwise by slowed down by subdividing the
calculation by group. In these circumstances, the calculation should be
independent of the grouping. with_ungroup()
temporarily removes groups,
applies the function .f
to .data
(as .f(.data)
) and then restores
the original grouping. This function is fastest when the applied function
does not modify the row order or the value of grouping columns. In these
cases, the group index will need to be recalculated adding computational
overhead depending on the number of rows and groups in the data.
1 | with_ungroup(.data, .f, ...)
|
.data |
A grouped tbl, tibble, or data.frame |
.f |
A function, formula, or vector (not necessarily atomic). If a function, it is used as is. If a formula, e.g.
This syntax allows you to create very compact anonymous functions. If character vector, numeric vector, or list, it is
converted to an extractor function. Character vectors index by
name and numeric vectors index by position; use a list to index
by position and name at different levels. If a component is not
present, the value of |
... |
Additional arguments passed on to methods. |
Other Group Utilities: group_drop
,
with_retain_groups
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # with_ungroup() ungroups the input data frame, applies the inner function,
# and restores grouping on output
tidyr::table1 %>%
dplyr::group_by(country, year) %>%
with_ungroup(~ dplyr::mutate(., r = cases / population))
# Groups that "disappear" are implicitly dropped, with a warning
tidyr::table1 %>%
dplyr::group_by(country, year) %>%
with_ungroup(~ {
dplyr::mutate(., r = cases/population) %>%
dplyr::select(-year)
})
# Works like "normal" if no groupings are present
tidyr::table1 %>%
with_ungroup(~ dplyr::mutate(., r = cases/population))
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.