Skip to contents

Table creation

All gt tables begin with a call to gt(), where we would supply the input data table (data frame or tibble) and some basic options for creating a stub (rowname_col) and row groups (groupname_col). We can also introduce a grouped tibble (via dplyr::group_by()) for more precise divisions of rows into row groups. gt_preview() is great for getting a nicely-formatted preview of a data table (defaulting to the first 5 rows and the last row).

gt()
Create a gt table object
gt_preview()
Generate a special gt table for previewing a dataset

Creating or modifying parts of a table

A gt table can contain a few useful parts for conveying additional information. These include a header (with a titles and subtitle), a footer (with footnotes and source notes), and additional areas for labels (row group labels, column spanner labels, the stubhead label). We can modify the look of table parts more generally with tab_options() and perform styling on targeted table locations with tab_style().

tab_header()
Add a table header
tab_spanner()
Add a spanner label
tab_spanner_delim()
Create column labels and spanners via delimited column names
tab_row_group()
Add a row group to a gt table
tab_stubhead()
Add label text to the stubhead
tab_stub_indent()
Control indentation of row labels in the stub
tab_footnote()
Add a table footnote
tab_source_note()
Add a source note citation
tab_caption()
Add a table caption
tab_style()
Add custom styles to one or more cells
tab_style_body()
Target cells in the table body and style accordingly
tab_options()
Modify the table output options
tab_info()
Understand what's been set inside of a gt table object

Formatting column data

Columns of data can be formatted with the fmt_*() functions. We can specify the rows of these columns quite precisely with the rows argument. We get to apply these functions exactly once to each data cell (last call wins). Need to do custom formatting? Use the fmt() function and define your own formatter within (or, create a wrapper with fmt() if you prefer). The sub_*() functions allow you to perform substitution operations and data_color() provides a lot of power for colorizing body cells based on their data values.

fmt_number()
Format numeric values
fmt_integer()
Format values as integers
fmt_scientific()
Format values to scientific notation
fmt_engineering()
Format values to engineering notation
fmt_percent()
Format values as a percentage
fmt_partsper()
Format values as parts-per quantities
fmt_fraction()
Format values as mixed fractions
fmt_currency()
Format values as currencies
fmt_roman()
Format values as Roman numerals
fmt_index()
Format values to indexed characters
fmt_spelled_num()
Format values to spelled-out numbers
fmt_bytes()
Format values as bytes
fmt_date()
Format values as dates
fmt_time()
Format values as times
fmt_datetime()
Format values as datetimes
fmt_duration()
Format numeric or duration values as styled time duration strings
fmt_bins()
Format column data containing bin/interval information
fmt_tf()
Format TRUE and FALSE values
fmt_markdown()
Format Markdown text
fmt_units()
Format measurement units
fmt_chem()
Format chemical formulas
fmt_url()
Format URLs to generate links
fmt_email()
Format email addresses to generate 'mailto:' links
fmt_image()
Format image paths to generate images in cells
fmt_flag()
Generate flag icons for countries from their country codes
fmt_country()
Generate country names from their corresponding country codes
fmt_icon()
Use icons within a table's body cells
fmt_passthrough()
Format by simply passing data through
fmt_auto()
Automatically format column data according to their values
fmt()
Set a column format with a formatter function
sub_missing()
Substitute missing values in the table body
sub_zero()
Substitute zero values in the table body
sub_small_vals()
Substitute small values in the table body
sub_large_vals()
Substitute large values in the table body
sub_values()
Substitute targeted values in the table body
data_color()
Perform data cell colorization

Text transformation

The text_*() functions take cell data that are solidified into strings and allow for flexible transformations of those string values. Whereas the fmt_*() and sub_*() are phases 1 and 2 of cell data metamorphoses, the text transformation functions are the final phase, acting on strings generated by formatting and substitution functions with no reference to the source values.

text_replace()
Perform highly targeted text replacement with a regex pattern
text_case_when()
Perform whole text replacements using a 'case-when'-expression approach
text_case_match()
Perform whole or partial text replacements with a 'switch'-like approach
text_transform()
Perform text transformations with a custom function

Modifying columns

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 (the cols_merge*() functions), and moving columns around (the cols_move*() functions).

cols_align()
Set the alignment of columns
cols_align_decimal()
Align all numeric values in a column along the decimal mark
cols_width()
Set the widths of columns
cols_label()
Relabel one or more columns
cols_label_with()
Relabel columns with a function
cols_units()
Define units for one or more columns
cols_add()
Add one or more columns to a gt table
cols_nanoplot()
Add a new column of nanoplots, taking input data from selected columns
cols_move()
Move one or more columns
cols_move_to_start()
Move one or more columns to the start
cols_move_to_end()
Move one or more columns to the end
cols_hide()
Hide one or more columns
cols_unhide()
Unhide one or more columns
cols_merge()
Merge data from two or more columns to a single column
cols_merge_uncert()
Merge columns to a value-with-uncertainty column
cols_merge_range()
Merge two columns to a value range column
cols_merge_n_pct()
Merge two columns to combine counts and percentages

Adding or modifying rows

There are two functions that will add rows to a gt table: summary_rows() and grand_summary_rows(). These functions will both add summary rows but one will do it in a groupwise fashion while the other will create grand summary rows. The row_group_order() function lets us modify the ordering of any row groups in the table.

summary_rows()
Add group-wise summary rows using aggregation functions
grand_summary_rows()
Add grand summary rows using aggregation functions
row_group_order()
Modify the ordering of any row groups
rows_add()
Add one or more rows to a gt table

Removing parts of a table

The rm_*() functions let us safely remove parts of a gt table. This can be advantageous in those instances where you would obtain a gt table but prefer to excise some parts of it.

rm_header()
Remove the table header
rm_stubhead()
Remove the stubhead label
rm_spanners()
Remove column spanner labels
rm_footnotes()
Remove table footnotes
rm_source_notes()
Remove table source notes
rm_caption()
Remove the table caption

FAQ

Many gt functions share parameters that behave more or less the same way. These topics explain the design principles of some of them.

rows-columns
Apply conditional formatting to cells with rows and columns
locale
Localize formatting and symbols
location-helper
Helper to target cells at locations
fmts
Formatting functions

Helper functions

An assortment of helper functions is available in the gt package. The various cells_*() functions are used for targeting cells with the locations argument of tab_footnote(), tab_style(), and text_transform(), text_case_match(), and text_case_when(). The cell_*() functions are used exclusively with tab_style()’s style argument. px() & pct() are useful there for specifying units in pixels or percentages. The md() and html() helpers can used be during label creation with tab_header(), tab_footnote(), tab_spanner(), tab_stubhead(), and tab_source_note().

md()
Interpret input text as Markdown-formatted text
html()
Interpret input text as HTML-formatted text
px()
Helper for providing a numeric value as pixels value
pct()
Helper for providing a numeric value as percentage
from_column()
Reference a column of values for certain parameters
currency()
Supply a custom currency symbol to fmt_currency()
unit_conversion()
Get a conversion factor across two measurement units of a given class
nanoplot_options()
Supply nanoplot options to cols_nanoplot()
adjust_luminance()
Adjust the luminance for a palette of colors
stub()
Select helper for targeting the stub column
row_group()
Select helper for targeting the row group column
cells_body()
Location helper for targeting data cells in the table body
cells_column_labels()
Location helper for targeting the column labels
cells_column_spanners()
Location helper for targeting the column spanners
cells_footnotes()
Location helper for targeting the footnotes
cells_grand_summary()
Location helper for targeting cells in a grand summary
cells_row_groups()
Location helper for targeting row groups
cells_source_notes()
Location helper for targeting the source notes
cells_stub()
Location helper for targeting cells in the table stub
cells_stub_grand_summary()
Location helper for targeting the stub cells in a grand summary
cells_stub_summary()
Location helper for targeting the stub cells in a summary
cells_stubhead()
Location helper for targeting the table stubhead cell
cells_summary()
Location helper for targeting group summary cells
cells_title()
Location helper for targeting the table title and subtitle
cell_text()
Helper for defining custom text styles for table cells
cell_fill()
Helper for defining custom fills for table cells
cell_borders()
Helper for defining custom borders for table cells
random_id()
Helper for creating a random id for a gt table
escape_latex()
Perform LaTeX escaping
gt_latex_dependencies()
Get the LaTeX dependencies required for a gt table
google_font()
Helper function for specifying a font from the Google Fonts service
default_fonts()
Provide a vector of sensible system fonts for use with gt tables
system_fonts()
Get a themed font stack that works well across systems

Image addition utilities

We can add images into a gt table with the help of the *_image() functions. Two common ways to do this: (1) use text_transform() to insert images into data cells, (2) use any function that creates new labels (e.g., tab_header()) and use a *_image() function within the html() helper.

web_image()
Helper function for adding an image from the web
local_image()
Helper function for adding a local image
ggplot_image()
Helper function for adding a ggplot
test_image()
Generate a path to a test image

Table options

With the opt_*() functions, we have an easy way to set commonly-used table options without having to use tab_options() directly. Like, we can quickly add a stylizing theme with opt_stylize(), get an interactive HTML table with opt_interactive(), modify the appearance of footnote marks with opt_footnote_marks() and opt_footnote_spec(), turn on row striping, change the alignment of the table header, and so much more.

opt_stylize()
Stylize your table with a colorful look
opt_interactive()
Option to put interactive elements in an HTML table
opt_footnote_marks()
Option to modify the set of footnote marks
opt_footnote_spec()
Option to specify the formatting of footnote marks
opt_row_striping()
Option to add or remove row striping
opt_align_table_header()
Option to align the table header
opt_vertical_padding()
Option to expand or contract vertical padding
opt_horizontal_padding()
Option to expand or contract horizontal padding
opt_all_caps()
Option to use all caps in select table locations
opt_table_lines()
Option to set table lines to different extents
opt_table_outline()
Option to wrap an outline around the entire table
opt_table_font()
Options to define font choices for the entire table
opt_css()
Option to add custom CSS for the table

Informational tables for reference

These info_*() functions present us with gt tables containing useful information. So far, we can get reference information on date styles (info_date_style()), on time styles (info_time_style()), on a huge number of color palettes (info_paletteer()), on currencies (info_currencies()), on all of the different locales supported in the formatter functions (info_locales()), and on our recommendations for which Google Fonts to try in your tables (info_google_fonts()).

info_date_style()
View a table with info on date styles
info_time_style()
View a table with info on time styles
info_currencies()
View a table with info on supported currencies
info_locales()
View a table with info on supported locales
info_paletteer()
View a table with info on color palettes
info_google_fonts()
View a table on recommended Google Fonts
info_flags()
View a table with all available flags for fmt_flag()
info_icons()
View a table with all available Font Awesome icons for fmt_icon()
info_unit_conversions()
View a table with all units that can be converted by unit_conversion()

Shiny

Shiny is great for building interactive web apps with R. There’s really nothing quite like it. The gt package includes two functions that work nicely with Shiny: a table render function render_gt() (for the server) and a table output element gt_output() (for the ui).

render_gt()
A gt display table render function for use in Shiny
gt_output()
Create a gt display table output element for Shiny

Export and extraction functions

There may come a day when you need to export a gt table to some specific format. A great function for that is gtsave(), which allows us to save the table as a standalone HTML, LaTeX, RTF, .docx, or even an image file. Some other functions give us table code as a character vector (e.g., as_raw_html() and more). Did you use the summary_rows() function and wish you had that summary data in a tibble? You can get it out with extract_summary(). Want to extract already-formatted cells from the table into a vector? Do it with extract_cells()! It’s even possible to extract the body of a table as a data frame during various ‘build’ stages (do this with extract_body()).

gtsave()
Save a gt table as a file
as_raw_html()
Get the HTML content of a gt table
as_latex()
Output a gt object as LaTeX
as_rtf()
Output a gt object as RTF
as_word()
Output a gt object as Word
as_gtable()
Transform a gt table to a gtable object
extract_body()
Extract the table body from a gt object
extract_summary()
Extract a summary list from a gt object
extract_cells()
Extract a vector of formatted cells from a gt object

Working with table groups

Sometimes you want to deal with a multitude of gt tables, all at once. There are some advantages to having a group of tables bundled together in a gt_group object. You could apply options that pertain to all tables yet still access the individual tables to give them their own specialized modifications. They all print altogether at once too! For HTML, each table will be separated by a line break whereas in paginated formats the tables are separated by page breaks.

gt_group()
Create a gt_group container for holding multiple gt table objects
gt_split()
Split a table into a group of tables (a gt_group)
grp_pull()
Pull out a gt table from a gt_group container object
grp_add()
Add one or more gt tables to a gt_group container object
grp_clone()
Clone one or more gt tables in a gt_group container object
grp_replace()
Replace one or more gt tables in a gt_group container object
grp_rm()
Remove one or more gt tables from a gt_group container object
grp_options()
Modify table options for all tables within a gt_group object

Vector formatting

Why should columns have all the formatting fun? If you have vectors in need of formatting, we have a set of vec_fmt_*() functions that have been adapted from the corresponding fmt_*() functions.

vec_fmt_number()
Format a vector as numeric values
vec_fmt_integer()
Format a vector as integer values
vec_fmt_scientific()
Format a vector as values in scientific notation
vec_fmt_engineering()
Format a vector as values in engineering notation
vec_fmt_percent()
Format a vector as percentage values
vec_fmt_partsper()
Format a vector as parts-per quantities
vec_fmt_fraction()
Format a vector as mixed fractions
vec_fmt_currency()
Format a vector as currency values
vec_fmt_roman()
Format a vector as Roman numerals
vec_fmt_index()
Format a vector as indexed characters
vec_fmt_spelled_num()
Format a vector as spelled-out numbers
vec_fmt_bytes()
Format a vector as values in terms of bytes
vec_fmt_date()
Format a vector as date values
vec_fmt_time()
Format a vector as time values
vec_fmt_datetime()
Format a vector as datetime values
vec_fmt_duration()
Format a vector of numeric or duration values as styled time duration strings
vec_fmt_markdown()
Format a vector containing Markdown text

Built in datasets

The gt package is equipped with 18 datasets that come in all shapes and sizes. Use them to experiment with the package! Many examples in the documentation use these datasets to demonstrate the awesome features of gt.

countrypops
Yearly populations of countries from 1960 to 2023
sza
Twice hourly solar zenith angles by month & latitude
gtcars
Deluxe automobiles from the 2014-2017 period
sp500
Daily S&P 500 Index data from 1950 to 2015
pizzaplace
A year of pizza sales from a pizza place
exibble
A toy example tibble for testing with gt: exibble
towny
Populations of all municipalities in Ontario from 1996 to 2021
peeps
A table of personal information for people all over the world
films
Feature films in competition at the Cannes Film Festival
metro
The stations of the Paris Metro
gibraltar
Weather conditions in Gibraltar, May 2023
constants
The fundamental physical constants
illness
Lab tests for one suffering from an illness
reactions
Reaction rates for gas-phase atmospheric reactions of organic compounds
photolysis
Data on photolysis rates for gas-phase organic compounds
nuclides
Nuclide data
rx_adsl
An ADSL-flavored clinical trial toy dataset
rx_addv
An ADDV-flavored clinical trial toy dataset