Add proportions by group

add_proportion(
  x,
  y,
  ...,
  name = "p",
  percent_format = FALSE,
  percent_accuracy = 0.01
)

Arguments

x

A data frame, data frame extension (e.g. a tibble), or a lazy data frame (e.g. from dbplyr or dtplyr).

y

Variable to calculate proportions from.

...

<data-masking> Variables to group by.

name

The name of the new column in the output.

If omitted, it will default to n. If there's already a column called n, it will error, and require you to specify the name.

percent_format

A logical. If TRUE, transform the numeric decimal into a readable percent of class character as a new column; {name}_format. If this parameter is missing it will default to the last column of the dataset passed in.

percent_accuracy

A numeric. If percent_format is TRUE, number to round the decimal to. Uses scales::percent() accuracy method for transformations.

Value

An object of the same type as x. The output has the same groups as the input.

Examples

mtcars %>% dplyr::count(cyl) %>% add_proportion(n)
#> # A tibble: 3 x 3 #> cyl n p #> <dbl> <int> <dbl> #> 1 4 11 0.344 #> 2 6 7 0.219 #> 3 8 14 0.438