with_retain_groups: Restore Groups After Applying a Function to a Data Frame

Description Usage Arguments See Also Examples

Description

Groups are sometimes removed by dplyr functions, such as dplyr::summarize(). However, it may be necessary to ensure that the data output by a function retains as many of the original groups as are available after applying the function. with_retain_groups() applies a function to a grouped data frame and restores the original group as much as possible.

Usage

1
with_retain_groups(.data, .f, ...)

Arguments

.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. ~ .x + 2, it is converted to a function. There are three ways to refer to the arguments:

  • For a single argument function, use .

  • For a two argument function, use .x and .y

  • For more arguments, use ..1, ..2, ..3 etc

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 .default will be returned.

...

Additional arguments passed on to methods.

See Also

Other Group Utilities: group_drop, with_ungroup

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# with_retain_groups() applies inner function to grouped data frame
# and restores grouping on output
tidyr::table1 %>%
  dplyr::group_by(country, year) %>%
  with_retain_groups(~ dplyr::summarize(., cases = sum(cases)))

# Groups that "disappear" are implicitly dropped, with a warning
tidyr::table1 %>%
  dplyr::group_by(country, year) %>%
  with_retain_groups(~ {
    dplyr::summarize(., r = cases / population) %>%
      dplyr::summarize(r = mean(r))
  })

# Works like "normal" if no groupings are present
tidyr::table1 %>%
  with_retain_groups(~ dplyr::mutate(., r = cases / population))

GerkeLab/fcds documentation built on July 30, 2020, 7:04 p.m.