The cols_*() functions allow for modifications that act on entire columns. This includes alignment of the data in columns (cols_align()), hiding columns from view (cols_hide()), re-labeling the column labels (cols_label()), merging two columns together (cols_merge*()), moving columns around (cols_move*()), and using a column name delimiter to create labels in the column spanner (cols_split_delim()).
cols_align()cols_label()cols_width()cols_move()cols_hide()cols_merge_range()cols_merge_uncert()cols_merge_n_pct()cols_merge()cols_align(): Set the alignment of columnscols_align(
data,
align = c("auto", "left", "center", "right"),
columns = everything()
)
The individual alignments of columns (which includes the column labels and all of their data cells) can be modified. We have the option to align text to the left, the center, and the right. In a less explicit manner, we can allow gt to automatically choose the alignment of each column based on the data type (with the auto option).
Use countrypops to create a gt table. Align the population column data to the left.
countrypops %>%
dplyr::select(-contains("code")) %>%
dplyr::filter(country_name == "Mongolia") %>%
tail(5) %>%
gt() %>%
cols_align(
align = "left",
columns = population
)
| country_name | year | population |
|---|---|---|
| Mongolia | 2013 | 2869107 |
| Mongolia | 2014 | 2923896 |
| Mongolia | 2015 | 2976877 |
| Mongolia | 2016 | 3027398 |
| Mongolia | 2017 | 3075647 |
cols_label(): Relabel one or more columnscols_label(
.data,
...,
.list = list2(...)
)
Column labels can be modified from their default values (the names of the columns from the input table data). When you create a gt table object using gt(), column names effectively become the column labels. While this serves as a good first approximation, column names aren’t often appealing as column labels in a gt output table. The cols_label() function provides the flexibility to relabel one or more columns and we even have the option to use the md() of html() helper functions for rendering column labels from Markdown or using HTML.
Use countrypops to create a gt table; label all the table’s columns to present better.
countrypops %>%
dplyr::select(-contains("code")) %>%
dplyr::filter(country_name == "Mongolia") %>%
tail(5) %>%
gt() %>%
cols_label(
country_name = "Name",
year = "Year",
population = "Population"
)
| Name | Year | Population |
|---|---|---|
| Mongolia | 2013 | 2869107 |
| Mongolia | 2014 | 2923896 |
| Mongolia | 2015 | 2976877 |
| Mongolia | 2016 | 3027398 |
| Mongolia | 2017 | 3075647 |
Use countrypops to create a gt table; label columns as before but make them bold with markdown formatting.
countrypops %>%
dplyr::select(-contains("code")) %>%
dplyr::filter(country_name == "Mongolia") %>%
tail(5) %>%
gt() %>%
cols_label(
country_name = md("**Name**"),
year = md("**Year**"),
population = md("**Population**")
)
| Name | Year | Population |
|---|---|---|
| Mongolia | 2013 | 2869107 |
| Mongolia | 2014 | 2923896 |
| Mongolia | 2015 | 2976877 |
| Mongolia | 2016 | 3027398 |
| Mongolia | 2017 | 3075647 |
cols_width(): Set the widths of columnscols_width(
.data,
...,
.list = list2(...)
)
Manual specifications of column widths can be performed using the cols_width() function. We choose which columns get specific widths (in pixels, usually by use of the px() helper function). Width assignments are supplied in ... through two-sided formulas, where the left-hand side defines the target columns and the right-hand side is a single width value in pixels.
Use exibble to create a gt table. With named arguments in ..., we can specify the exact widths for table columns (using everything() will capture all remaining columns).
exibble %>%
dplyr::select(
num, char, date,
datetime, row
) %>%
gt() %>%
cols_width(
num ~ px(150),
ends_with("r") ~ px(100),
starts_with("date") ~ px(200),
everything() ~ px(60)
)
| num | char | date | datetime | row |
|---|---|---|---|---|
| 1.111e-01 | apricot | 2015-01-15 | 2018-01-01 02:22 | row_1 |
| 2.222e+00 | banana | 2015-02-15 | 2018-02-02 14:33 | row_2 |
| 3.333e+01 | coconut | 2015-03-15 | 2018-03-03 03:44 | row_3 |
| 4.444e+02 | durian | 2015-04-15 | 2018-04-04 15:55 | row_4 |
| 5.550e+03 | NA | 2015-05-15 | 2018-05-05 04:00 | row_5 |
| NA | fig | 2015-06-15 | 2018-06-06 16:11 | row_6 |
| 7.770e+05 | grapefruit | NA | 2018-07-07 05:22 | row_7 |
| 8.880e+06 | honeydew | 2015-08-15 | NA | row_8 |
cols_move(): Move one or more columnscols_move(
data,
columns,
after
)
On those occasions where you need to move columns this way or that way, we can make use of the cols_move() function. While it’s true that the movement of columns can be done upstream of gt’s API, it is much easier and less error prone to use the function provided here. The movement procedure here takes one or more specified columns (in the columns argument) and places them to the right of a different column (the after argument). The ordering of the columns to be moved is preserved, as is the ordering of all other columns in the table.
Use countrypops to create a gt table; With the remaining columns, position population after country_name.
countrypops %>%
dplyr::select(-contains("code")) %>%
dplyr::filter(country_name == "Mongolia") %>%
tail(5) %>%
gt() %>%
cols_move(
columns = population,
after = country_name
)
| country_name | population | year |
|---|---|---|
| Mongolia | 2869107 | 2013 |
| Mongolia | 2923896 | 2014 |
| Mongolia | 2976877 | 2015 |
| Mongolia | 3027398 | 2016 |
| Mongolia | 3075647 | 2017 |
cols_hide(): Hide one or more columnscols_hide(
data,
columns
)
The cols_hide() function allows us to hide one or more columns from appearing in the final output table. While it’s possible and often desirable to omit columns from the input table data before introduction to the gt() function, there can be cases where the data in certain columns is useful (as a column reference during formatting of other columns) but the final display of those columns is not necessary.
Use countrypops to create a gt table; Hide the columns country_code_2 and country_code_3.
countrypops %>%
dplyr::filter(country_name == "Mongolia") %>%
tail(5) %>%
gt() %>%
cols_hide(columns = c(country_code_2, country_code_3))
| country_name | year | population |
|---|---|---|
| Mongolia | 2013 | 2869107 |
| Mongolia | 2014 | 2923896 |
| Mongolia | 2015 | 2976877 |
| Mongolia | 2016 | 3027398 |
| Mongolia | 2017 | 3075647 |
Use countrypops to create a gt table and use the population column to provide the conditional placement of footnotes, then hide that column and one other.
countrypops %>%
dplyr::filter(country_name == "Mongolia") %>%
tail(5) %>%
gt() %>%
cols_hide(columns = c(country_code_3, population)) %>%
tab_footnote(
footnote = "Population above 3,000,000.",
locations = cells_body(
columns = year,
rows = population > 3000000
)
)
| country_name | country_code_2 | year |
|---|---|---|
| Mongolia | MN | 2013 |
| Mongolia | MN | 2014 |
| Mongolia | MN | 2015 |
| Mongolia | MN | 20161 |
| Mongolia | MN | 20171 |
|
1
Population above 3,000,000.
|
||
cols_merge_range(): Merge two columns to a value range columncols_merge_range(
data,
col_begin,
col_end,
sep = "--",
autohide = TRUE
)
The cols_merge_range() function is a specialized variant of the cols_merge() function. It operates by taking a two columns that constitute a range of values (col_begin and col_end) and merges them into a single column. What results is a column containing both values separated by a long dash (e.g., 12.0 — 20.0). The column specified in col_end is dropped from the output table
Use gtcars to create a gt table, keeping only the model, mpg_c, and mpg_h columns; merge the mpg columns together as a single range column (which is labeled as MPG, in italics).
gtcars %>%
dplyr::select(model, starts_with("mpg")) %>%
dplyr::slice(1:8) %>%
gt() %>%
cols_merge_range(
col_begin = mpg_c,
col_end = mpg_h
) %>%
cols_label(
mpg_c = md("*MPG*")
)
| model | MPG |
|---|---|
| GT | 11–18 |
| 458 Speciale | 13–17 |
| 458 Spider | 13–17 |
| 458 Italia | 13–17 |
| 488 GTB | 15–22 |
| California | 16–23 |
| GTC4Lusso | 12–17 |
| FF | 11–16 |
cols_merge_uncert(): Merge two columns to a value & uncertainty columncols_merge_uncert(
data,
col_val,
col_uncert,
sep = " +/- ",
autohide = TRUE
)
The cols_merge_uncert() function is a specialized variant of the cols_merge() function. It operates by taking a base value column (col_val) and an uncertainty column (col_uncert) and merges them into a single column. What results is a column with values and associated uncertainties (e.g., 12.0 ± 0.1), and, the column specified in col_uncert is dropped from the output table.
Use exibble to create a gt table, keeping only the currency and num columns; merge columns into one with a base value and uncertainty (after formatting the num column).
exibble %>%
dplyr::select(currency, num) %>%
dplyr::slice(1:7) %>%
gt() %>%
fmt_number(
columns = num,
decimals = 3,
use_seps = FALSE
) %>%
cols_merge_uncert(
col_val = currency,
col_uncert = num
) %>%
cols_label(currency = "value + uncert.")
| value + uncert. |
|---|
| 49.950 ± 0.111 |
| 17.950 ± 2.222 |
| 1.390 ± 33.330 |
| 65100.000 ± 444.400 |
| 1325.810 ± 5550.000 |
| 13.255 |
| NA |
cols_merge_n_pct(): Merge two columns to combine counts and percentagescols_merge_uncert(
data,
col_n,
col_pct,
autohide = TRUE
)
The cols_merge_n_pct() function is a specialized variant of the cols_merge() function. It operates by taking two columns that constitute both a count (col_n) and a fraction of the total population (col_pct) and merges them into a single column. What results is a column containing both counts and their associated percentages (e.g., 12 (23.2%)). The column specified in col_pct is dropped from the output table.
Use pizzaplace to create a gt table that displays the counts and percentages of the top 3 pizzas sold by pizza category in 2015. The cols_merge_n_pct() function is used to merge the n and frac columns (and the frac column is formatted using fmt_percent()).
pizzaplace %>%
dplyr::group_by(name, type, price) %>%
dplyr::summarize(
n = dplyr::n(),
frac = n/nrow(.),
.groups = "drop"
) %>%
dplyr::arrange(type, dplyr::desc(n)) %>%
dplyr::group_by(type) %>%
dplyr::slice_head(n = 3) %>%
gt(
rowname_col = "name",
groupname_col = "type"
) %>%
fmt_integer(n) %>%
fmt_percent(frac) %>%
cols_merge_n_pct(
col_n = n,
col_pct = frac
) %>%
fmt_currency(price) %>%
cols_label(
n = md("*N*<br>(%)"),
price = md("Price<br>*(USD)*")
) %>%
tab_style(
style = cell_text(font = "monospace"),
locations = cells_stub()
) %>%
tab_stubhead(md("Cat. and \nPizza Code")) %>%
tab_header(title = "Top 3 Pizzas Sold by Category in 2015") %>%
tab_options(table.width = px(512))
| Top 3 Pizzas Sold by Category in 2015 | ||
|---|---|---|
| Cat. and Pizza Code |
Price (USD) |
N (%) |
| chicken | ||
| thai_ckn | $20.75 | 1,410 (2.84%) |
| southw_ckn | $20.75 | 1,016 (2.05%) |
| bbq_ckn | $20.75 | 992 (2.00%) |
| classic | ||
| big_meat | $12.00 | 1,914 (3.86%) |
| classic_dlx | $16.00 | 1,181 (2.38%) |
| hawaiian | $10.50 | 1,020 (2.06%) |
| supreme | ||
| spicy_ital | $20.75 | 1,109 (2.24%) |
| ital_supr | $16.50 | 941 (1.90%) |
| sicilian | $12.25 | 751 (1.51%) |
| veggie | ||
| five_cheese | $18.50 | 1,409 (2.84%) |
| four_cheese | $17.95 | 1,316 (2.65%) |
| mexicana | $20.25 | 867 (1.75%) |
cols_merge(): Merge data from two or more columns to a single columncols_merge(
data,
columns,
hide_columns = columns[-1],
pattern = paste0("{", seq_along(columns), "}", collapse = " ")
)
This function takes input from two or more columns and allows the contents to be merged them into a single column, using a pattern that specifies the formatting. We can specify which columns to merge together in the columns argument. The string-combining pattern is given in the pattern argument. The first column in the columns series operates as the target column (i.e., will undergo mutation) whereas all following columns will be untouched.
Use sp500 to create a gt table; merge the open & close columns together, and, the low & high columns (putting an em dash between both); rename the columns.
sp500 %>%
dplyr::slice(50:55) %>%
dplyr::select(-volume, -adj_close) %>%
gt() %>%
cols_merge(
columns = c(open, close),
hide_columns = close,
pattern = "{1} - {2}"
) %>%
cols_merge(
columns = c(low, high),
hide_columns = high,
pattern = "{1} - {2}"
) %>%
cols_label(
open = "open/close",
low = "low/high"
)
| date | open/close | low/high |
|---|---|---|
| 2015-10-21 | 2033.47 - 2018.94 | 2017.22 - 2037.97 |
| 2015-10-20 | 2033.13 - 2030.77 | 2026.61 - 2039.12 |
| 2015-10-19 | 2031.73 - 2033.66 | 2022.31 - 2034.45 |
| 2015-10-16 | 2024.37 - 2033.11 | 2020.46 - 2033.54 |
| 2015-10-15 | 1996.47 - 2023.86 | 1996.47 - 2024.15 |
| 2015-10-14 | 2003.66 - 1994.24 | 1990.73 - 2009.56 |
cols_align() function.cols_label() (they otherwise inherit column names from the input dataset).cols_width() (HTML output only, for now); use the px() and pct() helpers to make this easier.cols_move().cols_hide(); this is good when you a column for something but don’t want to display it in the end.cols_merge_range().cols_merge_uncert().cols_merge() and a pattern ({1} + {2}...)