Creating Summary Lines

We can use gt::summary_rows() to insert summary rows into a table. There are two main types of summary rows: (1) group-wise summaries, and (2) the grand summary. The group-wise summaries operate on one or more row groups, which can themselves be generated in a variety of ways:

  • with the gt() function's groupname_col option
  • using tab_row_group() on a gt object
  • by passing in a grouped tbl_df object to gt() (using dplyr::group_by())

We generate the summary data through specification of aggregation functions. You choose how to format the values in the resulting summary cells by use of a formatter function (e.g., fmt_number()) and any relevant options. These summary rows are automatically inserted within the relevant row groups (for group-wise summaries) or at the bottom of the table (as a grand summary), where each summary row is the result of a different aggregation function.

Preparing the Input Data Table

Let's use the exibble dataset (included in the gt package) to demonstrate how summary rows can be added. That table contains categorical columns named row and group, along several columns with varying data types. Here is a preview of the exibble dataset using solely the gt() function with no other options:

import tabelline, tabelline/datasets, gtdata

let preview = tabella(exibble())
nbTable preview
numcharfctrdatetimedatetimecurrencyrowgroup
0.1111apricotone2015-01-1513:352018-01-01 02:2249.95row_1grp_a
2.222bananatwo2015-02-1514:402018-02-02 14:3317.95row_2grp_a
33.33coconutthree2015-03-1515:452018-03-03 03:441.39row_3grp_a
444.4durianfour2015-04-1516:502018-04-04 15:5565100.0row_4grp_a
5550.0five2015-05-1517:552018-05-05 04:001325.81row_5grp_b
figsix2015-06-152018-06-06 16:1113.255row_6grp_b
777000.0grapefruitseven19:102018-07-07 05:22row_7grp_b
8880000.0honeydeweight2015-08-1520:200.44row_8grp_b

We'll create a table stub with both row labels (using the row column) and row groups (using the group column). The end result will be a table organized with labeled rows that are grouped together (the row group labels identify each of the row groups). To make the examples a bit easier to follow, some of the columns in exibble will first be dropped through a dplyr::select() statement.

# Create a table using the `exibble` dataset
let exibbleA = tabella(exibble().select(["num", "char", "currency", "row", "group"]),
                       rownameCol = "row", groupnameCol = "group"):
  subMissing()
nbTable exibbleA
numcharcurrency
grp_a
row_10.1111apricot49.95
row_22.222banana17.95
row_333.33coconut1.39
row_4444.4durian65100.0
grp_b
row_55550.0—1325.81
row_6—fig13.255
row_7777000.0grapefruit—
row_88880000.0honeydew0.44

There are two groups in this data table: grp_a and grp_b. This gives us flexibility to create both a grand summary and group-wise summary rows.

Generating Group-wise Summary Rows

Group-wise summary rows can be generated by using summary_rows() and, importantly, through specifying the groups that will receive summary rows. We can provide a vector group names, as in c("grp_a", "grp_b"), or, use everything() to signify that all groups should receive summary rows. Aside from the selection of groups, there is control over which columns are to used for the summary. Since each call to summary_rows() only performs one set of aggregation functions, we may want specific aggregations for different subsets of columns.

To make any sort of summary, we need to use functions that will perform the aggregation. We can provide base functions such as mean(), sum(), min(), max(), and more, within a list(). Each function provided will result in a summary row for each group.

Because each function will yield a row, we need to be able to label that row. So, each summary row will receive a summary row label. We can provide our preferred names by naming the functions within the list (e.g, list(average = "mean", total = "sum", SD = "sd")).

# Create group-wise summary rows for both groups (all of
# them, by default); use the mean, the sum and the
# standard deviation (only for the `num` column)
let exibbleB = tabella(exibbleA):
  summaryRows:
    average: agg.mean
    total: agg.sum
    SD: agg.std
    columns = "num"
nbTable exibbleB
numcharcurrency
grp_a
row_10.1111apricot49.95
row_22.222banana17.95
row_333.33coconut1.39
row_4444.4durian65100.0
average120.02——
total480.06——
SD216.79——
grp_b
row_55550.0—1325.81
row_6—fig13.255
row_7777000.0grapefruit—
row_88880000.0honeydew0.44
average3,220,850.00——
total9,662,550.00——
SD4,916,123.25——

We can specify the aggregation functions by use of function names in quotes (e.g., "sum"), as bare functions (e.g., sum), or as one-sided R formulas using a leading ~. In the formula representation, a . serves as the data to be summarized, so we can use sum(., na.rm = TRUE). The use of named arguments is recommended as those names will serve as summary row labels (the labels can derived from the function names but only when not providing bare function names).

Now that summary_rows() has been somewhat explained, let’s look at how we can create group-wise summary rows for the exibble_a table. We'll create summaries for both available groups (groups = everything()) and use the mean(), sum(), and sd() functions with the function-name-in-quotes method (and this will only pertain to the num column).

In the previous example we have an NA value in the num/row_6 cell, and so we get NA outputs from mean(), sum(), and sd() in grp_b's summary rows (which are replaced with em dashes, itself controllable through the missing_text option). To avoid this, let's rewrite the above using the names-and-formulae method.

# The aggregates leave out missing values already;
# only the labels change
let exibbleC = tabella(exibbleA):
  summaryRows:
    avg: agg.mean
    total: agg.sum
    "s.d.": agg.std
    columns = "num"
nbTable exibbleC
numcharcurrency
grp_a
row_10.1111apricot49.95
row_22.222banana17.95
row_333.33coconut1.39
row_4444.4durian65100.0
avg120.02——
total480.06——
s.d.216.79——
grp_b
row_55550.0—1325.81
row_6—fig13.255
row_7777000.0grapefruit—
row_88880000.0honeydew0.44
avg3,220,850.00——
total9,662,550.00——
s.d.4,916,123.25——

Here we see that summary rows were created for both groups. However, the output of the summary row data is quite different than that of the cell data. The formatter argument (and extra ... arguments) allows for use of any of the fmt_*() functions that we'd normally use to format cell data. In this example (another rewrite of the above), the cell data in the num column is formatted in scientific notation and the resulting summary cell data is also formatted in the same way (including the options of decimals = 3).

# Define a list of aggregates and
# summary row labels
let fnsLabels = @{"avg": agg.mean, "total": agg.sum, "s.d.": agg.std}

# Create group-wise summary rows as before, with
# `fnsLabels`, and format the summary cells
let exibbleD = tabella(exibbleA):
  fmtScientific "num", decimals = 3
  summaryRows fnsLabels, columns = "num",
    fmt = proc (x: float): string = formatScientific(x, decimals = 3)
nbTable exibbleD
numcharcurrency
grp_a
row_11.111 × 10−1apricot49.95
row_22.222banana17.95
row_33.333 × 101coconut1.39
row_44.444 × 102durian65100.0
avg1.200 × 10²——
total4.801 × 10²——
s.d.2.168 × 10²——
grp_b
row_55.550 × 103—1325.81
row_6—fig13.255
row_77.770 × 105grapefruit—
row_88.880 × 106honeydew0.44
avg3.221 × 10⁶——
total9.663 × 10⁶——
s.d.4.916 × 10⁶——

The input to fns is very permissive in regard to how the functions are defined. It is entirely valid to provide functions in the various forms shown earlier such that list("sum", avg = ~mean(., na.rm = TRUE), SD = "sd") will be correctly interpreted. It is recommended to use formula notation.

The default for formatter is set to fmt_number which is a sensible default for many scenarios. The setting of argument values for a particular formatter can be done in the ... area of the function call (as was done above for the decimals argument).

Using Multiple Calls of summary_rows()

We can re-use summary row labels and fill the otherwise empty summary cells with similar aggregations but perhaps with different formatting options. Here's an example where the currency column contains aggregate values that share the same summary rows as for the num column, adds two more rows, and uses currency formatting:

let exibbleE = tabella(exibbleA):
  fmtScientific "num", decimals = 3
  fmtCurrency "currency", currency = "EUR"
  summaryRows fnsLabels, columns = "num",
    fmt = proc (x: float): string = formatScientific(x, decimals = 3)
  summaryRows fnsLabels & @{"min": agg.min, "max": agg.max},
    groups = ["grp_a"], columns = "currency",
    fmt = proc (x: float): string = formatCurrency(x, "EUR")
nbTable exibbleE
numcharcurrency
grp_a
row_11.111 × 10−1apricot€49.95
row_22.222banana€17.95
row_33.333 × 101coconut€1.39
row_44.444 × 102durian€65,100.00
avg1.200 × 10²—€16,292.32
total4.801 × 10²—€65,169.29
s.d.2.168 × 10²—€32,538.46
min——€1.39
max——€65,100.00
grp_b
row_55.550 × 103—€1,325.81
row_6—fig€13.26
row_77.770 × 105grapefruit—
row_88.880 × 106honeydew€0.44
avg3.221 × 10⁶——
total9.663 × 10⁶——
s.d.4.916 × 10⁶——

A thing to again note in the above example is that even though two independent calls of summary_rows() were made, summary data within common summary row names were 'squashed' together, thus avoiding the fragmentation of summary rows. Put another way, we don't create additional summary rows across separate calls if we are referencing the same summary row labels. If the summary row labels provided in fns were to be different across columns however, additional summary rows would be produced even if the types of data aggregations were to be functionally equivalent.

We can also store these argument values as local variables and pass them in both separate fmt_*number*() calls also to arguments within summary_rows() calls. This is useful for standardizing formatting parameters across different table cell types. Here's an example of that, which additional passes the fr_BE locale to all functions that take a locale value.

# Common formatting parameters, in a tuple
const formats = (decimals: 3, locale: "fr_BE", currency: "EUR")

let exibbleF = tabella(exibbleA):
  fmtScientific "num", decimals = formats.decimals, locale = formats.locale
  fmtCurrency "currency", currency = formats.currency, locale = formats.locale
  summaryRows fnsLabels, columns = "num",
    fmt = proc (x: float): string =
      formatScientific(x, decimals = formats.decimals, locale = formats.locale)
  summaryRows fnsLabels & @{"min": agg.min, "max": agg.max},
    groups = ["grp_a"], columns = "currency",
    fmt = proc (x: float): string =
      formatCurrency(x, currency = formats.currency, locale = formats.locale)
nbTable exibbleF
numcharcurrency
grp_a
row_11,111 × 10−1apricot49,95 €
row_22,222banana17,95 €
row_33,333 × 101coconut1,39 €
row_44,444 × 102durian65 100,00 €
avg1,200 × 10²—16 292,32 €
total4,801 × 10²—65 169,29 €
s.d.2,168 × 10²—32 538,46 €
min——1,39 €
max——65 100,00 €
grp_b
row_55,550 × 103—1 325,81 €
row_6—fig13,26 €
row_77,770 × 105grapefruit—
row_88,880 × 106honeydew0,44 €
avg3,221 × 10⁶——
total9,663 × 10⁶——
s.d.4,916 × 10⁶——

Passing in parameters like this is useful, especially if there are larger numbers of columns. When we store formatting parameters outside of the gt() pipeline, we separate our concerns between data structuring and data formatting. Putting styles and options into objects becomes more important if we intend to centralize formatting options for reuse.

Creating a Grand Summary

A grand summary aggregates column data regardless of the groups within the data. Grand summaries can also be created for gt tables that don't have row groups, or, don't have a stub. Finally, we can create a table that has both group-wise summaries and a grand summary.

Let's keep it simple and create grand summary rows on a table without a stub. We'll use exibble dataset for this once more. A few exibble columns are select()ed, passed to gt(), and then grand_summary_rows(). Notice that, in the resulting table, a stub is created just for the summary row labels (they have to go somewhere).

# Create a simple grand summary on a
# table that contains no stub
let exibbleG = tabella(exibble().select(["num", "char", "currency"])):
  grandSummaryRows fnsLabels, columns = cols("num", "currency")
nbTable exibbleG
numcharcurrency
0.1111apricot49.95
2.222banana17.95
33.33coconut1.39
444.4durian65100.0
5550.01325.81
fig13.255
777000.0grapefruit
8880000.0honeydew0.44
avg1,380,432.87—9,501.26
total9,663,030.06—66,508.80
s.d.3,319,613.32—24,521.60

A grand summary can be used in conjunction with group-wise summaries. Here's an table where both types of summaries are present:

# Using the table in `exibbleF`, create grand
# summary rows (two calls, one per format)
let exibbleH = tabella(exibbleF):
  grandSummaryRows fnsLabels, columns = "num",
    fmt = proc (x: float): string = formatCompact(x, 2, decMark = ",")
  grandSummaryRows fnsLabels, columns = "currency",
    fmt = proc (x: float): string = formatCompact(x, 2, decMark = ",") & " €"
nbTable exibbleH
numcharcurrency
grp_a
row_11,111 × 10−1apricot49,95 €
row_22,222banana17,95 €
row_33,333 × 101coconut1,39 €
row_44,444 × 102durian65 100,00 €
avg1,200 × 10²—16 292,32 €
total4,801 × 10²—65 169,29 €
s.d.2,168 × 10²—32 538,46 €
min——1,39 €
max——65 100,00 €
grp_b
row_55,550 × 103—1 325,81 €
row_6—fig13,26 €
row_77,770 × 105grapefruit—
row_88,880 × 106honeydew0,44 €
avg3,221 × 10⁶——
total9,663 × 10⁶——
s.d.4,916 × 10⁶——
avg1,38M—9,5K €
total9,66M—66,51K €
s.d.3,32M—24,52K €

Note that the grand summary has a double line separating it from group-wise summary that's part of grp_b. If this default styling appears to be too subtle, we can elect to add further styling to both group-wise summaries and the grand summary by using tab_options().

Adding Some Style to the Summary Cells

While the summary cells (both group-wise and grand) have a distinct appearance that sets them apart from the data cells, there's always the option to modify their appearance. We can use tab_options() to perform these customizations. Here are the options specific to the summary cells (for group-wise summaries) and the grand summary cells:

  • summary_row.background.color & grand_summary_row.background.color
  • summary_row.padding & grand_summary_row.padding
  • summary_row.text_transform & grand_summary_row.text_transform

We can also target the summary cells and grand summary cells with the location helper functions cells_summary() and cells_grand_summary(). This is important for adding footnotes with tab_footnote() and for setting styles with tab_style() (both have the locations argument).

Here is an example that uses multiple calls of tab_options() and tab_footnote(). The cell background color for both types of summary cells is modified and two footnotes are added.

let exibbleI = tabella(exibbleH):
  tabOptions:
    summaryRowBackgroundColor = "lightblue"
    grandSummaryRowBackgroundColor = "lightgreen"
  tabFootnote md"Mean of all *num* values.",
    loc.grandSummary(columns = "num", rows = ["avg"])
  tabFootnote md"Highest `currency` value in **grp_a**",
    loc.summary(groups = ["grp_a"], columns = "currency", rows = ["max"])
nbTable exibbleI
numcharcurrency
grp_a
row_11,111 × 10−1apricot49,95 €
row_22,222banana17,95 €
row_33,333 × 101coconut1,39 €
row_44,444 × 102durian65 100,00 €
avg1,200 × 10²—16 292,32 €
total4,801 × 10²—65 169,29 €
s.d.2,168 × 10²—32 538,46 €
min——1,39 €
max——65 100,00 €1
grp_b
row_55,550 × 103—1 325,81 €
row_6—fig13,26 €
row_77,770 × 105grapefruit—
row_88,880 × 106honeydew0,44 €
avg3,221 × 10⁶——
total9,663 × 10⁶——
s.d.4,916 × 10⁶——
avg1,38M2—9,5K €
total9,66M—66,51K €
s.d.3,32M—24,52K €
1 Highest currency value in grp_a
2 Mean of all num values.

Extracting the Summary Data from the gt Table Object

For a reproducible workflow, we do not want to have situations where any data created or modified cannot be accessed. While having summarized values be created in a gt pipeline presents advantages to readability and intent of analysis, it is recognized that the output table itself is essentially 'read only', as the input data undergoes processing and movement to an entirely different format.

However, the object created still contains data and we can obtain the summary data from a gt table object with extract_summary(). Taking the gt_summary object, we get a list of tibbles containing the summary data while preserving the correct data types:

# Extract the summary rows of `exibbleD`
# as a table of their own
let summaryData = extractSummary(exibbleD)

# Show the summary of the `grp_a` group
let grpA = tabella(summaryData):
  rowsHide where(it.group != "grp_a")
nbTable grpA
grouplabelnumcharcurrency
grp_aavg1.200 × 10²——
grp_atotal4.801 × 10²——
grp_as.d.2.168 × 10²——
# Show the summary of the `grp_b` group
let grpB = tabella(summaryData):
  rowsHide where(it.group != "grp_b")
nbTable grpB
grouplabelnumcharcurrency
grp_bavg3.221 × 10⁶——
grp_btotal9.663 × 10⁶——
grp_bs.d.4.916 × 10⁶——

The output tibbles within the list always contain the groupname and rowname columns. The groupname column is filled with the name of the row group that was given to summary_rows(). The rowname column contains the descriptive stub labels for the summary rows (recall that values are either supplied explicitly in summary_rows(), or, are generated from the function names). The remaining columns are those from the original dataset.

The output data from extract_summary() can be reintroduced to a reproducible workflow and serve as downstream inputs or undergo validation. Perhaps interestingly, the output tibbles are structured in a way that facilitates direct input back to gt() (i.e., it has the magic groupname and rowname columns). This can produce a new, standalone summary table where the summary rows are now data rows:

# The summary rows of `exibbleD` as a table of their
# own, grouped and labelled as they were
let standalone = tabella(extractSummary(exibbleD, values = true), rownameCol = "label",
                         groupnameCol = "group"):
  fmtNumber "num", decimals = 1
  subMissing()
nbTable standalone
numcharcurrency
grp_a
avg120.0——
total480.1——
s.d.216.8——
grp_b
avg3,220,850.0——
total9,662,550.0——
s.d.4,916,123.3——

Providing Our Own Aggregation Functions to Generate Summary Rows

While many of the functions available in base R and within packages are useful as aggregate functions, we may occasionally have the need to create our own custom functions. When taking this approach the main things to keep in mind are that a vector of values is the main input, and, a single value should be returned. The return value can be pretty much any class (e.g., numeric, character, logical) and it's the formatter function that will handle any custom formatting while also converting to character.

Here, we'll define a function that takes a vector of numeric values and outputs the two highest values (sorted low to high) above a threshold value. The output from this function is always a formatted character string.

import std/[algorithm, math, sequtils, strutils]

# Define a proc that gives the highest
# two values above a threshold
proc aggHighestTwoAboveValue(x: seq[float], threshold: float): string =
  # Get sorted values above threshold value
  let values = x.filterIt(it >= threshold).mapIt(round(it, 2)).sorted
  # Return a string with the 2 highest values above threshold
  if values.len == 0:
    "No values above " & $threshold
  else:
    values[max(0, values.len - 2) .. ^1].mapIt(it.formatFloat(ffDecimal, 2)).join(", ")

# Let's test this proc with some values
echo aggHighestTwoAboveValue(@[0.73, 0.93, 0.75, 0.86, 0.23, 0.81], threshold = 0.8)
0.86, 0.93

Because this is character value that's returned, we don't need formatting functions like fmt_number(), fmt_percent(), etc. However, a useful formatter (and we do need some formatter) is fmt_passthrough(). Like the name suggests, it to great extent passes values through but formats as character (like all the fmt_*() function do) and it provides the option to decorate the output with a pattern. Let's have a look at how agg_highest_two_above_value() can be used with fmt_passthrough().

# A grand summary of `num` and `currency` with the custom proc and
# a threshold of 20; `fmt`, a proc of a value, puts it in parentheses
let exibbleJ = tabella(exibbleA):
  grandSummaryRows:
    high: aggregate(proc (vs: seq[Value]): string =
      aggHighestTwoAboveValue(vs.mapIt(it.toFloat), threshold = 20))
    columns = cols("num", "currency")
    fmt = proc (v: Value): string = "(" & $v & ")"
nbTable exibbleJ
numcharcurrency
grp_a
row_10.1111apricot49.95
row_22.222banana17.95
row_333.33coconut1.39
row_4444.4durian65100.0
grp_b
row_55550.0—1325.81
row_6—fig13.255
row_7777000.0grapefruit—
row_88880000.0honeydew0.44
high(777000.00, 8880000.00)—(1325.81, 65100.00)

We can extract the grand summary data from the exibble_j object. Note that columns num and currency are classed as character since it was character outputs that were generated by the agg_highest_two_above_value() function.

# Extract the summary rows of `exibbleJ`, and print them
echo tabella(extractSummary(exibbleJ, values = true))
┌───────┬───────┬───────────────────────┬──────┬───────────────────┐
│ group │ label │ num                   │ char │ currency          │
╞═══════╪═══════╪═══════════════════════╪══════╪═══════════════════╡
│       │ high  │ 777000.00, 8880000.00 │      │ 1325.81, 65100.00 │
└───────┴───────┴───────────────────────┴──────┴───────────────────┘
import tabbook
bookInit()

nbText: "# Creating Summary Lines"

attribution gtVignette("Creating Summary Lines", "creating-summary-lines",
  "The R chunks are the article's own; the Python tab writes them with Polars expressions, " &
  "which is how Great Tables takes its aggregates.")

nbText: """
We can use `gt::summary_rows()` to insert summary rows into a table. There are two main types of summary rows: (1) group-wise summaries, and (2) the grand summary. The group-wise summaries operate on one or more row groups, which can themselves be generated in a variety of ways:

- with the `gt()` function's `groupname_col` option
- using `tab_row_group()` on a gt object
- by passing in a grouped `tbl_df` object to `gt()` (using `dplyr::group_by()`)

We generate the summary data through specification of aggregation functions. You choose how to format the values in the resulting summary cells by use of a formatter function (e.g., `fmt_number()`) and any relevant options. These summary rows are automatically inserted within the relevant row groups (for group-wise summaries) or at the bottom of the table (as a grand summary), where each summary row is the result of a different aggregation function.

### Preparing the Input Data Table

Let's use the `exibble` dataset (included in the **gt** package) to demonstrate how summary rows can be added. That table contains categorical columns named `row` and `group`, along several columns with varying data types. Here is a preview of the `exibble` dataset using solely the `gt()` function with no other options:
"""

tabs """
import polars as pl
from functools import partial
from great_tables import GT, exibble, loc, md, vals

GT(exibble)
""", """
library(gt)
library(dplyr)

exibble |> gt()
""":
  nbCode:
    import tabelline, tabelline/datasets, gtdata

    let preview = tabella(exibble())
    nbTable preview

nbText: """
We'll create a table stub with both row labels (using the `row` column) and row groups (using the `group` column). The end result will be a table organized with labeled rows that are grouped together (the row group labels identify each of the row groups). To make the examples a bit easier to follow, some of the columns in exibble will first be dropped through a `dplyr::select()` statement.
"""

tabs """
# Create a GT table using the `exibble` dataset
exibble_pl = pl.from_pandas(exibble).drop(["fctr", "date", "time", "datetime"])

exibble_a = GT(exibble_pl, rowname_col="row", groupname_col="group").sub_missing()

exibble_a
""", """
# Create a gt table using the `exibble` dataset
exibble_a <-
  exibble |>
  select(-c(fctr, date, time, datetime)) |>
  gt(rowname_col = "row", groupname_col = "group") |>
  sub_missing()

exibble_a
""":
  nbCode:
    # Create a table using the `exibble` dataset
    let exibbleA = tabella(exibble().select(["num", "char", "currency", "row", "group"]),
                           rownameCol = "row", groupnameCol = "group"):
      subMissing()
    nbTable exibbleA

tabelline """
tabelline makes tables, not data: the book's `select` (`gtdata`) keeps the columns named, where
dplyr drops the ones named.
"""

nbText: """
There are two groups in this data table: `grp_a` and `grp_b`. This gives us flexibility to create both a grand summary and group-wise summary rows.

### Generating Group-wise Summary Rows

Group-wise summary rows can be generated by using `summary_rows()` and, importantly, through specifying the groups that will receive summary rows. We can provide a vector group names, as in `c("grp_a", "grp_b")`, or, use `everything()` to signify that all groups should receive summary rows. Aside from the selection of groups, there is control over which columns are to used for the summary. Since each call to `summary_rows()` only performs one set of aggregation functions, we may want specific aggregations for different subsets of columns.

To make any sort of summary, we need to use functions that will perform the aggregation. We can provide base functions such as `mean()`, `sum()`, `min()`, `max()`, and more, within a `list()`. Each function provided will result in a summary row for each `group`.

Because each function will yield a row, we need to be able to label that row. So, each summary row will receive a summary row label. We can provide our preferred names by naming the functions within the list (e.g, `list(average = "mean", total = "sum", SD = "sd")`).
"""

tabs """
# Create group-wise summary rows for both
# groups (the default); use the mean, the sum
# and the standard deviation (only of `num`)
exibble_b = exibble_a.summary_rows(
    fns={
        "average": pl.col("num").mean(),
        "total": pl.col("num").sum(),
        "SD": pl.col("num").std(),
    }
)

exibble_b
""", """
# Create group-wise summary rows for both
# groups (using `groups = everything()`); use the
# `mean()`, `sum()`, and `sd()` functions
# (only for the `num` column)
exibble_b <-
  exibble_a |>
  summary_rows(
    groups = everything(),
    columns = num,
    fns = list(
      average = "mean",
      total = "sum",
      SD = "sd"
    )
  )

exibble_b
""":
  nbCode:
    # Create group-wise summary rows for both groups (all of
    # them, by default); use the mean, the sum and the
    # standard deviation (only for the `num` column)
    let exibbleB = tabella(exibbleA):
      summaryRows:
        average: agg.mean
        total: agg.sum
        SD: agg.std
        columns = "num"
    nbTable exibbleB

tabelline """
The aggregates are in the `agg` namespace (`agg.mean`, `agg.sum`, `agg.std`, `agg.min`,
`agg.max`, `agg.median`, `agg.count`), and they leave out missing values, as Polars does. So
`grp_b` gets its numbers here and in Python, where gt's `mean()` gives `NA` (the dash): what
the next example does with `na.rm = TRUE` tabelline and Great Tables do already.
"""

nbText: """
We can specify the aggregation functions by use of function names in quotes (e.g., `"sum"`), as bare functions (e.g., `sum`), or as one-sided R formulas using a leading `~`. In the formula representation, a `.` serves as the data to be summarized, so we can use `sum(., na.rm = TRUE)`. The use of named arguments is recommended as those names will serve as summary row labels (the labels can derived from the function names but only when not providing bare function names).

Now that `summary_rows()` has been somewhat explained, let’s look at how we can create group-wise summary rows for the `exibble_a` table. We'll create summaries for both available groups (`groups = everything()`) and use the `mean()`, `sum()`, and `sd()` functions with the _function-name-in-quotes_ method (and this will only pertain to the `num` column).

In the previous example we have an `NA` value in the `num/row_6` cell, and so we get `NA` outputs from `mean()`, `sum()`, and `sd()` in `grp_b`'s summary rows (which are replaced with em dashes, itself controllable through the `missing_text` option). To avoid this, let's rewrite the above using the _names-and-formulae_ method.
"""

tabs """
# Polars leaves out missing values already;
# only the labels change
exibble_c = exibble_a.summary_rows(
    fns={
        "avg": pl.col("num").mean(),
        "total": pl.col("num").sum(),
        "s.d.": pl.col("num").std(),
    }
)

exibble_c
""", """
# Create group-wise summary rows for both
# groups (using `groups = everything()`); we will
# use names and formulas this time in `fns`
exibble_c <-
  exibble_a |>
  summary_rows(
    groups = everything(),
    columns = num,
    fns = list(
      avg = ~ mean(., na.rm = TRUE),
      total = ~ sum(., na.rm = TRUE),
      s.d. = ~ sd(., na.rm = TRUE)
    )
  )

exibble_c
""":
  nbCode:
    # The aggregates leave out missing values already;
    # only the labels change
    let exibbleC = tabella(exibbleA):
      summaryRows:
        avg: agg.mean
        total: agg.sum
        "s.d.": agg.std
        columns = "num"
    nbTable exibbleC

nbText: """
Here we see that summary rows were created for both groups. However, the output of the summary row data is quite different than that of the cell data. The `formatter` argument (and extra `...` arguments) allows for use of any of the `fmt_*()` functions that we'd normally use to format cell data. In this example (another rewrite of the above), the cell data in the `num` column is formatted in scientific notation and the resulting summary cell data is also formatted in the same way (including the options of `decimals = 3`).
"""

tabs """
# Define a dictionary of aggregates and
# summary row labels, for any columns
def fns_labels(*columns):
    return {
        "avg": pl.col(*columns).mean(),
        "total": pl.col(*columns).sum(),
        "s.d.": pl.col(*columns).std(),
    }

exibble_d = (
    exibble_a
    .fmt_scientific(columns="num", decimals=3)
    .summary_rows(
        fns=fns_labels("num"),
        fmt=partial(vals.fmt_scientific, decimals=3),
    )
)

exibble_d
""", """
# Define a named list of aggregation
# functions and summary row labels
fns_labels <-
  list(
    avg = ~ mean(., na.rm = TRUE),
    total = ~ sum(., na.rm = TRUE),
    s.d. = ~ sd(., na.rm = TRUE)
  )

# Create group-wise summary rows as
# before, supply `fns_labels` to `fns`,
# and format the cell summary data
exibble_d <-
  exibble_a |>
  fmt_scientific(
    columns = num,
    decimals = 3
  ) |>
  summary_rows(
    groups = everything(),
    columns = num,
    fns = fns_labels,
    fmt = list(~ fmt_scientific(., decimals = 3))
  )

exibble_d
""":
  nbCode:
    # Define a list of aggregates and
    # summary row labels
    let fnsLabels = @{"avg": agg.mean, "total": agg.sum, "s.d.": agg.std}

    # Create group-wise summary rows as before, with
    # `fnsLabels`, and format the summary cells
    let exibbleD = tabella(exibbleA):
      fmtScientific "num", decimals = 3
      summaryRows fnsLabels, columns = "num",
        fmt = proc (x: float): string = formatScientific(x, decimals = 3)
    nbTable exibbleD

tabelline """
A list of aggregates made once is a `seq` of pairs, given as the first argument (the block
form is for pairs written in place). `fmt` is a proc of a float, here calling
`formatScientific`, the function behind `fmtScientific`. Without a `fmt`, a summary cell takes
the format of its column: `fmtScientific "num", decimals = 3` alone gives the same table.
"""

nbText: """
The input to `fns` is very permissive in regard to how the functions are defined. It is entirely valid to provide functions in the various forms shown earlier such that `list("sum", avg = ~mean(., na.rm = TRUE), SD = "sd")` will be correctly interpreted. It is recommended to use formula notation.

The default for `formatter` is set to `fmt_number` which is a sensible default for many scenarios. The setting of argument values for a particular formatter can be done in the `...` area of the function call (as was done above for the `decimals` argument).

### Using Multiple Calls of `summary_rows()`

We can re-use summary row labels and fill the otherwise empty summary cells with similar aggregations but perhaps with different formatting options. Here's an example where the `currency` column contains aggregate values that share the same summary rows as for the `num` column, adds two more rows, and uses currency formatting:
"""

tabs """
exibble_e = (
    exibble_a
    .fmt_scientific(columns="num", decimals=3)
    .fmt_currency(columns="currency", currency="EUR")
    .summary_rows(
        fns=fns_labels("num"),
        fmt=partial(vals.fmt_scientific, decimals=3),
    )
    .summary_rows(
        groups=["grp_a"],
        fns=fns_labels("currency")
        | {"min": pl.col("currency").min(), "max": pl.col("currency").max()},
        fmt=partial(vals.fmt_currency, currency="EUR"),
    )
)

exibble_e
""", """
# Create group-wise summary rows as
# before, supply `fns_labels` to `fns`,
# and format the cell summary data
exibble_e <-
  exibble_a |>
  fmt_scientific(
    columns = num,
    decimals = 3
  ) |>
  fmt_currency(
    columns = currency,
    currency = "EUR"
  ) |>
  summary_rows(
    groups = everything(),
    columns = num,
    fns = fns_labels,
    fmt = list(~ fmt_scientific(., decimals = 3))
  ) |>
  summary_rows(
    groups = "grp_a",
    columns = currency,
    fns = c(
      fns_labels,
      min = ~ min(.),
      max = ~ max(.)
    ),
    fmt = list(~ fmt_currency(., currency = "EUR"))
  )

exibble_e
""":
  nbCode:
    let exibbleE = tabella(exibbleA):
      fmtScientific "num", decimals = 3
      fmtCurrency "currency", currency = "EUR"
      summaryRows fnsLabels, columns = "num",
        fmt = proc (x: float): string = formatScientific(x, decimals = 3)
      summaryRows fnsLabels & @{"min": agg.min, "max": agg.max},
        groups = ["grp_a"], columns = "currency",
        fmt = proc (x: float): string = formatCurrency(x, "EUR")
    nbTable exibbleE

nbText: """
A thing to again note in the above example is that even though two independent calls of `summary_rows()` were made, summary data within common summary row names were 'squashed' together, thus avoiding the fragmentation of summary rows. Put another way, we don't create additional summary rows across separate calls if we are referencing the same summary row labels. If the summary row labels provided in `fns` were to be different across columns however, additional summary rows would be produced even if the types of data aggregations were to be functionally equivalent.

We can also store these argument values as local variables and pass them in both separate `fmt_*number*()` calls also to arguments within `summary_rows()` calls. This is useful for standardizing formatting parameters across different table cell types. Here's an example of that, which additional passes the `fr_BE` locale to all functions that take a `locale` value.
"""

tabelline """
tabelline squashes them too, as gt does: two calls of `summaryRows` with the same label make one
row, *avg* in *grp_a* for both `num` and `currency`. Great Tables adds a row for each call.
"""

tabs """
# Common formatting parameters, in a dictionary
formats = {"decimals": 3, "locale": "fr_BE", "currency": "EUR"}

exibble_f = (
    exibble_a
    .fmt_scientific(columns="num", decimals=formats["decimals"], locale=formats["locale"])
    .fmt_currency(columns="currency", currency=formats["currency"], locale=formats["locale"])
    .summary_rows(
        fns=fns_labels("num"),
        fmt=partial(vals.fmt_scientific, decimals=formats["decimals"], locale=formats["locale"]),
    )
    .summary_rows(
        groups=["grp_a"],
        fns=fns_labels("currency")
        | {"min": pl.col("currency").min(), "max": pl.col("currency").max()},
        fmt=partial(vals.fmt_currency, currency=formats["currency"], locale=formats["locale"]),
    )
)

exibble_f
""", """
# Provide common formatting parameters to a list
# object named `formats`; the number of decimal
# places will be `2` and the locale is "fr_BE"
formats <-
  list(
    decimals = 3,
    locale = "fr_BE",
    currency = "EUR"
  )

# Format the `num` and `currency` columns
# (using the values stored in `formats`);
# when generating summary rows we can also
# supply formatter options from this list
exibble_f <-
  exibble_a |>
  fmt_scientific(
    columns = num,
    decimals = formats$decimals,
    locale = formats$locale
  ) |>
  fmt_currency(
    columns = currency,
    currency = formats$currency,
    locale = formats$locale
  ) |>
  summary_rows(
    groups = everything(),
    columns = num,
    fns = fns_labels,
    fmt = list(~ fmt_scientific(.,
      decimals = formats$decimals,
      locale = formats$locale
    ))
  ) |>
  summary_rows(
    groups = "grp_a",
    columns = currency,
    fns = c(
      fns_labels,
      min = ~ min(.),
      max = ~ max(.)
    ),
    fmt = list(~ fmt_currency(.,
      currency = formats$currency,
      locale = formats$locale
    ))
  )

exibble_f
""":
  nbCode:
    # Common formatting parameters, in a tuple
    const formats = (decimals: 3, locale: "fr_BE", currency: "EUR")

    let exibbleF = tabella(exibbleA):
      fmtScientific "num", decimals = formats.decimals, locale = formats.locale
      fmtCurrency "currency", currency = formats.currency, locale = formats.locale
      summaryRows fnsLabels, columns = "num",
        fmt = proc (x: float): string =
          formatScientific(x, decimals = formats.decimals, locale = formats.locale)
      summaryRows fnsLabels & @{"min": agg.min, "max": agg.max},
        groups = ["grp_a"], columns = "currency",
        fmt = proc (x: float): string =
          formatCurrency(x, currency = formats.currency, locale = formats.locale)
    nbTable exibbleF

tabelline """
The format functions take the arguments of their verbs, `locale` too, so the `fmt` of each
summary is written as in R. Without a `fmt`, a summary cell takes the format of its column,
with its locale, which here gives the same table.
"""

nbText: """
Passing in parameters like this is useful, especially if there are larger numbers of columns. When we store formatting parameters outside of the `gt()` pipeline, we separate our concerns between data structuring and data formatting. Putting styles and options into objects becomes more important if we intend to centralize formatting options for reuse.

### Creating a Grand Summary

A grand summary aggregates column data regardless of the groups within the data. Grand summaries can also be created for **gt** tables that don't have row groups, or, don't have a stub. Finally, we can create a table that has both group-wise summaries and a grand summary.

Let's keep it simple and create grand summary rows on a table without a stub. We'll use `exibble` dataset for this once more. A few `exibble` columns are `select()`ed, passed to `gt()`, and then `grand_summary_rows()`. Notice that, in the resulting table, a stub is created just for the summary row labels (they have to go somewhere).
"""

tabs """
# Create a simple grand summary on a GT
# table that contains no stub
exibble_g = GT(pl.from_pandas(exibble).select(["num", "char", "currency"])).grand_summary_rows(
    fns=fns_labels("num", "currency"),
    fmt=vals.fmt_number,
)

exibble_g
""", """
# Create a simple grand summary on a gt
# table that contains no stub
exibble_g <-
  exibble |>
  select(num, char, currency) |>
  gt() |>
  grand_summary_rows(
    columns = c(num, currency),
    fns = fns_labels
  )

exibble_g
""":
  nbCode:
    # Create a simple grand summary on a
    # table that contains no stub
    let exibbleG = tabella(exibble().select(["num", "char", "currency"])):
      grandSummaryRows fnsLabels, columns = cols("num", "currency")
    nbTable exibbleG

tabelline """
gt formats summary cells with `fmt_number()` when it is given no `fmt`; Great Tables leaves
them as they are; tabelline uses the column's format, and a column with none shows the number
as it is (an `agg.count` as an integer).
"""

nbText: """
A grand summary can be used in conjunction with group-wise summaries. Here's an table where both types of summaries are present:
"""

tabs """
exibble_h = (
    exibble_f
    .grand_summary_rows(
        fns=fns_labels("num"),
        fmt=partial(vals.fmt_number, compact=True, locale=formats["locale"]),
    )
    .grand_summary_rows(
        fns=fns_labels("currency"),
        fmt=partial(vals.fmt_currency, currency=formats["currency"], compact=True,
                    locale=formats["locale"]),
    )
)

exibble_h
""", """
# Using the table in `exibble_f`, create
# grand summary rows (using two separate
# calls of `grand_summary_rows()` since
# the formatting will be different)
exibble_h <-
  exibble_f |>
  grand_summary_rows(
    columns = num,
    fns = fns_labels,
    fmt = list(~ fmt_number(.,
      suffixing = TRUE,
      locale = formats$locale
    ))
  ) |>
  grand_summary_rows(
    columns = currency,
    fns = fns_labels,
    fmt = list(~ fmt_currency(.,
      suffixing = TRUE,
      locale = formats$locale
    ))
  )

exibble_h
""":
  nbCode:
    # Using the table in `exibbleF`, create grand
    # summary rows (two calls, one per format)
    let exibbleH = tabella(exibbleF):
      grandSummaryRows fnsLabels, columns = "num",
        fmt = proc (x: float): string = formatCompact(x, 2, decMark = ",")
      grandSummaryRows fnsLabels, columns = "currency",
        fmt = proc (x: float): string = formatCompact(x, 2, decMark = ",") & " €"
    nbTable exibbleH

nbText: """
Note that the grand summary has a double line separating it from group-wise summary that's part of `grp_b`. If this default styling appears to be too subtle, we can elect to add further styling to both group-wise summaries and the grand summary by using `tab_options()`.

### Adding Some Style to the Summary Cells

While the summary cells (both group-wise and grand) have a distinct appearance that sets them apart from the data cells, there's always the option to modify their appearance. We can use `tab_options()` to perform these customizations. Here are the options specific to the summary cells (for group-wise summaries) and the grand summary cells:

- `summary_row.background.color` & `grand_summary_row.background.color`
- `summary_row.padding` & `grand_summary_row.padding`
- `summary_row.text_transform` & `grand_summary_row.text_transform`

We can also target the summary cells and grand summary cells with the location helper functions `cells_summary()` and `cells_grand_summary()`. This is important for adding footnotes with `tab_footnote()` and for setting styles with `tab_style()` (both have the `locations` argument).

Here is an example that uses multiple calls of `tab_options()` and `tab_footnote()`. The cell background color for both types of summary cells is modified and two footnotes are added.
"""

tabs """
exibble_i = (
    exibble_h
    .tab_options(
        summary_row_background_color="lightblue",
        grand_summary_row_background_color="lightgreen",
    )
    .tab_footnote(
        footnote=md("Mean of all *num* values."),
        locations=loc.grand_summary(columns="num", rows="avg"),
    )
    .tab_footnote(
        footnote=md("Highest `currency` value in **grp_a**"),
        locations=loc.summary(groups="grp_a", columns="currency", rows="max"),
    )
)

exibble_i
""", """
# Using the gt table of `exibble_h` as a
# starting point, style summary cells with
# `tab_options()` and add two footnotes
exibble_i <-
  exibble_h |>
  tab_options(
    summary_row.background.color = "lightblue",
    grand_summary_row.background.color = "lightgreen"
  ) |>
  tab_footnote(
    footnote = md("Mean of all *num* values."),
    locations = cells_grand_summary(
      columns = "num", rows = "avg"
    )
  ) |>
  tab_footnote(
    footnote = md("Highest `currency` value in **grp_a**"),
    locations = cells_summary(
      groups = "grp_a",
      columns = "currency",
      rows = "max"
    )
  )

exibble_i
""":
  nbCode:
    let exibbleI = tabella(exibbleH):
      tabOptions:
        summaryRowBackgroundColor = "lightblue"
        grandSummaryRowBackgroundColor = "lightgreen"
      tabFootnote md"Mean of all *num* values.",
        loc.grandSummary(columns = "num", rows = ["avg"])
      tabFootnote md"Highest `currency` value in **grp_a**",
        loc.summary(groups = ["grp_a"], columns = "currency", rows = ["max"])
    nbTable exibbleI

nbText: """
### Extracting the Summary Data from the **gt** Table Object

For a reproducible workflow, we do not want to have situations where any data created or modified cannot be accessed. While having summarized values be created in a **gt** pipeline presents advantages to readability and intent of analysis, it is recognized that the output table itself is essentially 'read only', as the input data undergoes processing and movement to an entirely different format.

However, the object created still contains data and we can obtain the summary data from a **gt** table object with `extract_summary()`. Taking the `gt_summary` object, we get a list of tibbles containing the summary data while preserving the correct data types:
"""

tabs "", """
# Extract the summary data from `exibble_d`
# to a list  object
summary_list <- exibble_d |> extract_summary()

# Print out the summary for the `grp_a` group
summary_list$summary_df_data_list$grp_a
""":
  nbCode:
    # Extract the summary rows of `exibbleD`
    # as a table of their own
    let summaryData = extractSummary(exibbleD)

    # Show the summary of the `grp_a` group
    let grpA = tabella(summaryData):
      rowsHide where(it.group != "grp_a")
    nbTable grpA

tabs "", """
# Print out the summary for the `grp_b` group
summary_list$summary_df_data_list$grp_b
""":
  nbCode:
    # Show the summary of the `grp_b` group
    let grpB = tabella(summaryData):
      rowsHide where(it.group != "grp_b")
    nbTable grpB

tabelline """
Great Tables has no `extract_summary()`. tabelline's `extractSummary` gives one table for every
summary row, with the columns `group` and `label` (where gt has `groupname` and `rowname`),
and the cells as they are shown, formatted, where gt keeps the numbers.
"""

nbText: """
The output tibbles within the list always contain the `groupname` and `rowname` columns. The `groupname` column is filled with the name of the row group that was given to `summary_rows()`. The `rowname` column contains the descriptive stub labels for the summary rows (recall that values are either supplied explicitly in `summary_rows()`, or, are generated from the function names). The remaining columns are those from the original dataset.

The output data from `extract_summary()` can be reintroduced to a reproducible workflow and serve as downstream inputs or undergo validation. Perhaps interestingly, the output tibbles are structured in a way that facilitates direct input back to `gt()` (i.e., it has the magic `groupname` and `rowname` columns). This can produce a new, standalone summary table where the summary rows are now data rows:
"""

tabs "", """
# Take `exibble_d`, which internally has a list
# of summary data frames, extract the summaries,
# and then combine them; input that into `gt()`,
# and format the `num` column with `fmt_number()`
exibble_d |>
  extract_summary() |>
  unlist(recursive = FALSE) |>
  bind_rows() |>
  gt() |>
  fmt_number(
    columns = num,
    decimals = 1
  ) |>
  sub_missing(columns = c(char, currency, row, group))
""":
  nbCode:
    # The summary rows of `exibbleD` as a table of their
    # own, grouped and labelled as they were
    let standalone = tabella(extractSummary(exibbleD, values = true), rownameCol = "label",
                             groupnameCol = "group"):
      fmtNumber "num", decimals = 1
      subMissing()
    nbTable standalone

tabelline """
`extractSummary` gives the cells as shown (`2.926 × 10²` and so on); with `values = true` it
gives the numbers, which take a format again, as gt's do.
"""

nbText: """
### Providing Our Own Aggregation Functions to Generate Summary Rows

While many of the functions available in base R and within packages are useful as aggregate functions, we may occasionally have the need to create our own custom functions. When taking this approach the main things to keep in mind are that a vector of values is the main input, and, a single value should be returned. The return value can be pretty much any class (e.g., `numeric`, `character`, `logical`) and it's the `formatter` function that will handle any custom formatting while also converting to `character`.

Here, we'll define a function that takes a vector of numeric values and outputs the two highest values (sorted low to high) above a `threshold` value. The output from this function is always a formatted `character` string.
"""

tabs """
# Define a function that gives the
# highest two values above a threshold
def agg_highest_two_above_value(x, threshold):
    # Get sorted values above threshold value
    values = sorted(round(v, 2) for v in x if v is not None and v >= threshold)

    # Return string with 2 highest values above threshold
    if len(values) == 0:
        return f"No values above {threshold}"
    return ", ".join(f"{v:.2f}" for v in values[-2:])

# Let's test this function with some values
agg_highest_two_above_value([0.73, 0.93, 0.75, 0.86, 0.23, 0.81], threshold=0.8)
""", """
# Define a function that gives the
# highest two values above a threshold
agg_highest_two_above_value <- function(x, threshold) {
  # Get sorted values above threshold value
  values <- sort(round(x[x >= threshold], 2))

  # Return character string with 2 highest values above threshold
  if (length(values) == 0) {
    return(paste0("No values above ", threshold))
  } else {
    return(
      paste(
        formatC(
          tail(
            sort(round(x[x > threshold], 2)), 2
          ),
          format = "f", digits = 2
        ),
        collapse = ", "
      )
    )
  }
}

# Let's test this function with some values
agg_highest_two_above_value(
  x = c(0.73, 0.93, 0.75, 0.86, 0.23, 0.81),
  threshold = 0.8
)
""":
  nbCode:
    import std/[algorithm, math, sequtils, strutils]

    # Define a proc that gives the highest
    # two values above a threshold
    proc aggHighestTwoAboveValue(x: seq[float], threshold: float): string =
      # Get sorted values above threshold value
      let values = x.filterIt(it >= threshold).mapIt(round(it, 2)).sorted
      # Return a string with the 2 highest values above threshold
      if values.len == 0:
        "No values above " & $threshold
      else:
        values[max(0, values.len - 2) .. ^1].mapIt(it.formatFloat(ffDecimal, 2)).join(", ")

    # Let's test this proc with some values
    echo aggHighestTwoAboveValue(@[0.73, 0.93, 0.75, 0.86, 0.23, 0.81], threshold = 0.8)

nbText: """
Because this is character value that's returned, we don't need formatting functions like `fmt_number()`, `fmt_percent()`, etc. However, a useful formatter (and we do need *some* formatter) is `fmt_passthrough()`. Like the name suggests, it to great extent passes values through but formats as `character` (like all the `fmt_*()` function do) and it provides the option to decorate the output with a `pattern`. Let's have a look at how `agg_highest_two_above_value()` can be used with `fmt_passthrough()`.
"""

tabs """
# A summary of each column, with the custom function
# and a threshold of 20, written in parentheses
exibble_j = exibble_a.grand_summary_rows(
    fns={
        "high": pl.col("num", "currency").map_batches(
            lambda s: pl.Series([agg_highest_two_above_value(s.to_list(), 20)]),
            return_dtype=pl.String,
            returns_scalar=True,
        )
    },
    fmt=lambda xs: [f"({x})" for x in xs],
)

exibble_j
""", """
# Create a gt table with `exibble_a` and use
# the custom function with a threshold of `20`;
# `fmt_passthrough()` allows for minimal formatting
# of the aggregate values
exibble_j <-
  exibble_a |>
  grand_summary_rows(
    columns = c(num, currency),
    fns = list(high = ~ agg_highest_two_above_value(., 20)),
    fmt = list(~ fmt_passthrough(., pattern = "({x})"))
  )

exibble_j
""":
  nbCode:
    # A grand summary of `num` and `currency` with the custom proc and
    # a threshold of 20; `fmt`, a proc of a value, puts it in parentheses
    let exibbleJ = tabella(exibbleA):
      grandSummaryRows:
        high: aggregate(proc (vs: seq[Value]): string =
          aggHighestTwoAboveValue(vs.mapIt(it.toFloat), threshold = 20))
        columns = cols("num", "currency")
        fmt = proc (v: Value): string = "(" & $v & ")"
    nbTable exibbleJ

tabelline """
`aggregate` makes an aggregate of a proc of the non-missing values; it may return text, as here.
A `fmt` that is a proc of a value gets the text as it is, as `fmt_passthrough()` does.
"""

nbText: """
We can extract the grand summary data from the `exibble_j` object. Note that columns `num` and `currency` are classed as character since it was character outputs that were generated by the `agg_highest_two_above_value()` function.
"""

tabs "", """
# Extract the summary list from `exibble_j`
# and inspect using `str()`
exibble_j |>
  extract_summary() |>
  str()
""":
  nbCode:
    # Extract the summary rows of `exibbleJ`, and print them
    echo tabella(extractSummary(exibbleJ, values = true))

bookSave()
Made with tabelline, nimib and nimibook. The Nim code ran when this page was built; the Python ran with Great Tables 1.1.0 and the R with gt 1.4.0.