The grand_summary_rows() function

Use a modified version of the sp500 dataset to create a gt table with row groups and row labels. Create the grand summary rows min, max, and avg for the table with grand_summary_rows().

sp500 |>
  dplyr::filter(date >= "2015-01-05" & date <= "2015-01-16") |>
  dplyr::arrange(date) |>
  dplyr::mutate(week = paste0("W", strftime(date, format = "%V"))) |>
  dplyr::select(-adj_close, -volume) |>
  gt(
    rowname_col = "date",
    groupname_col = "week"
  ) |>
  grand_summary_rows(
    columns = c(open, high, low, close),
    fns = list(
      min ~ min(.),
      max ~ max(.),
      avg ~ mean(.)
    ),
    fmt = ~ fmt_number(., use_seps = FALSE)
  )
open high low close
W02
2015-01-05 2054.44 2054.44 2017.34 2020.58
2015-01-06 2022.15 2030.25 1992.44 2002.61
2015-01-07 2005.55 2029.61 2005.55 2025.90
2015-01-08 2030.61 2064.08 2030.61 2062.14
2015-01-09 2063.45 2064.43 2038.33 2044.81
W03
2015-01-12 2046.13 2049.30 2022.58 2028.26
2015-01-13 2031.58 2056.93 2008.25 2023.03
2015-01-14 2018.40 2018.40 1988.44 2011.27
2015-01-15 2013.75 2021.35 1991.47 1992.67
2015-01-16 1992.25 2020.46 1988.12 2019.42
min 1992.25 2018.40 1988.12 1992.67
max 2063.45 2064.43 2038.33 2062.14
avg 2027.83 2040.92 2008.31 2023.07

Let’s take the countrypops dataset and process that a bit before handing it off to gt. We can create a single grand summary row with totals that appears at the top of the table body (with side = "top"). We can define the aggregation with a list that contains parameters for the grand summary row label ("TOTALS"), the ID value of that row ("totals"), and the aggregation function (expressed as "sum", which gt recognizes as the sum() function). Finally, we’ll add a background fill to the grand summary row with tab_style().

countrypops |>
  dplyr::filter(country_code_2 %in% c("BE", "NL", "LU")) |>
  dplyr::filter(year %% 10 == 0) |>
  dplyr::select(country_name, year, population) |>
  tidyr::pivot_wider(names_from = year, values_from = population) |>
  gt(rowname_col = "country_name") |>
  tab_header(title = "Populations of the Benelux Countries") |>
  tab_spanner(columns = everything(), label = "Year") |>
  fmt_integer() |>
  grand_summary_rows(
    fns =  list(label = "TOTALS", id = "totals", fn = "sum"),
    fmt = ~ fmt_integer(.),
    side = "top"
  ) |>
  tab_style(
    locations = cells_grand_summary(),
    style = cell_fill(color = "lightblue" |> adjust_luminance(steps = +1))
  )
Populations of the Benelux Countries
Year
1960 1970 1980 1990 2000 2010 2020
TOTALS 20,954,090 23,033,246 24,373,192 25,300,739 26,613,063 28,017,933 29,610,523
Belgium 9,153,489 9,655,549 9,859,242 9,967,379 10,251,250 10,895,586 11,538,604
Luxembourg 313,970 339,171 364,150 381,850 436,300 506,953 630,419
Netherlands 11,486,631 13,038,526 14,149,800 14,951,510 15,925,513 16,615,394 17,441,500