Skip to contents

Summarise and include a total row, or a row including the summary for the whole group, into a factor list. This looks and feels like a natural summarisation step, but applies the summarisation both to the subgroups and to the data ungrouped by one level. The additional group result is included as a new row. allows for a natural grouped and ungrouped summarisation

Usage

summarise_with_totals(
  .data,
  ...,
  .groups = NULL,
  .total = "Total",
  .total_first = FALSE
)

Arguments

.data

a dataframe

...

the summarisation specification

.groups

what to do with the grouping after summarisation (same as dplyr::summarise)

.total

name of the total row which will be added into a factor list.

.total_first

should the total be before or after the groups

Value

a summarised dataframe with the additional totals or group row

Examples

library(tidyverse)
diamonds %>%
 dplyr::group_by(color,cut) %>%
 summarise_with_totals(
    mpg = sprintf("%1.1f \u00B1 %1.1f", mean(price), stats::sd(price)),
    .total = "Overall"
 )
#> # A tibble: 42 × 3
#> # Groups:   color [7]
#>    color cut       mpg            
#>    <fct> <fct>     <chr>          
#>  1 D     Fair      4291.1 ± 3286.1
#>  2 D     Good      3405.4 ± 3175.1
#>  3 D     Very Good 3470.5 ± 3523.8
#>  4 D     Premium   3631.3 ± 3711.6
#>  5 D     Ideal     2629.1 ± 3001.1
#>  6 E     Fair      3682.3 ± 2976.7
#>  7 E     Good      3423.6 ± 3330.7
#>  8 E     Very Good 3214.7 ± 3408.0
#>  9 E     Premium   3538.9 ± 3795.0
#> 10 E     Ideal     2597.6 ± 2956.0
#> # ℹ 32 more rows