With a subset of the towny dataset, we can create a gt table and then use tab_spanner_delim() to automatically generate column spanner labels. In this case we have some column names in the form population_<year>. The underscore character is the delimiter that separates a common word "population" and a year value. In this default way of splitting, fragments to the right are lowest (really they become new column labels) and moving left we get spanners. Let’s have a look at how tab_spanner_delim() handles these column names:
The spanner created through this use of tab_spanner_delim() is automatically given an ID value by gt. Because it’s hard to know what the ID value is, we can use tab_info() to inspect the table’s indices and ID values.
towny_subset_gt |>tab_info()
Information on ID and Label Values
ID
Idx Lvl
Label
Columns
name
1
name
population_1996
2
1996
population_2001
3
2001
population_2006
4
2006
population_2011
5
2011
population_2016
6
2016
population_2021
7
2021
Rows
<< Index values 1 to 7 >>
Spanners
spanner-population_1996
1
population
From this informational table, we see that the ID for the spanner is "spanner-population_1996". Also, the columns are still accessible by the original column names (tab_spanner_delim() did change their labels though). Let’s use tab_style() along with cells_column_spanners() to add some styling to the spanner label of the towny_subset_gt table.
We can plan ahead a bit and refashion the column names with dplyr before introducing the table to gt() and tab_spanner_delim(). Here the column labels have underscore delimiters where splitting is not wanted (so a period or space character is used instead). The usage of tab_spanner_delim() gives two levels of spanners. We can further touch up the labels after that with cols_label_with() and text_transform().
With a summarized, filtered, and pivoted version of the pizzaplace dataset, we can create another gt table and then use tab_spanner_delim() with the delimiter/separator also used in tidyr::pivot_wider(). We can also process the generated column labels with cols_label_with().