Introduction to Creating gt Tables (2024)

Introduction to Creating gt Tables (1)

Source: vignettes/gt.Rmd

gt.Rmd

The gt package is all about making it simple toproduce nice-looking display tables. Display tables? Well yes, we aretrying to distinguish between data tables (e.g., tibbles,data.frames, etc.) and those tables you’d find in a webpage, a journal article, or in a magazine. Such tables can likewise becalled presentation tables, summary tables, or just tables really. Hereare some examples, ripped straight from the web:

Introduction to Creating gt Tables (2)

We can think of display tables as output only, where we’d not want touse them as input ever again. Other features include annotations, tableelement styling, and text transformations that serve to communicate thesubject matter more clearly.

A Walkthrough of the gt Basics with a SimpleTable

Let’s use a less common dataset that is available in the Rdatasets package: islands. It’s actuallynot a data frame but a named vector. That’s okay though, we can use usedplyr and prepare a tibble from it:

# Take the `islands` dataset and use some# dplyr functionality to obtain the ten# biggest islands in the worldislands_tbl <-  tibble( name = names(islands), size = islands ) |> arrange(desc(size)) |> slice(1:10)# Display the tableislands_tbl#> # A tibble: 10 × 2#> name size#> <chr> <dbl>#>  1 Asia 16988#>  2 Africa 11506#>  3 North America 9390#>  4 South America 6795#>  5 Antarctica 5500#>  6 Europe 3745#>  7 Australia 2968#>  8 Greenland 840#>  9 New Guinea 306#> 10 Borneo 280

Given that islands_tbl is a tibble, we now have asuitable input for gt.

The main entry point into the gt API is thegt() function. If we pass islands_tbl to thefunction gt(), we’ll get a gtTable as output. As an aside, we could have easily used a dataframe instead as valid Table Data forgt.

# Create a display table showing ten of# the largest islands in the worldgt_tbl <- gt(islands_tbl)# Show the gt Tablegt_tbl
name size
Asia16988
Africa11506
North America9390
South America6795
Antarctica5500
Europe3745
Australia2968
Greenland840
New Guinea306
Borneo280

That doesn’t look too bad. Sure, it’s basic but we really didn’treally ask for much. We did receive a proper table with column labelsand the data. Also, that default striping is a nice touch. Oftentimeshowever, you’ll want a bit more: a Table header, aStub, and sometimes footnotes and sourcenotes in the Table Footer part.

Adding Parts to this Simple Table

The gt package makes it relatively easy to add partsso that the resulting gt Table better conveys theinformation you want to present. These table parts work well togetherand there the possible variations in arrangement can handle most tabularpresentation needs. The previous gt Table demonstratedhad only two parts, the Column Labels and theTable Body. The next few examples will show all of theother table parts that are available.

This is the way the main parts of a table (and their subparts) fittogether:

Introduction to Creating gt Tables (3)

The parts (roughly from top to bottom) are:

  • the Table Header (optional; with atitle and possibly a subtitle)
  • the Stub and the Stub Head(optional; contains row labels, optionally within rowgroups having row group labels and possibly summarylabels when a summary is present)
  • the Column Labels (contains column labels,optionally under spanner column labels)
  • the Table Body (contains columns androws of cells)
  • the Table Footer (optional; possibly withfootnotes and source notes)

The way that we add parts like the Table Header andfootnotes in the Table Footer is to use thetab_*() family of functions. A TableHeader is easy to add so let’s see how the previous table lookswith a title and a subtitle. We canadd this part using the tab_header() function:

# Make a display table with the `islands_tbl`# table; put a heading just above the column labelsgt_tbl <-  gt_tbl |> tab_header( title = "Large Landmasses of the World", subtitle = "The top ten largest are presented" )# Show the gt Tablegt_tbl
Large Landmasses of the World
The top ten largest are presented
name size
Asia16988
Africa11506
North America9390
South America6795
Antarctica5500
Europe3745
Australia2968
Greenland840
New Guinea306
Borneo280

The Header table part provides an opportunity todescribe the data that’s presented. The subtitle, whichfunctions as a subtitle, is an optional part of theHeader. We may also style the title andsubtitle using Markdown! We do this by wrapping the valuespassed to title or subtitle with themd() function. Here is an example with the table datatruncated for brevity:

# Use markdown for the heading's `title` and `subtitle` to# add bold and italicized charactersgt(islands_tbl[1:2,]) |> tab_header( title = md("**Large Landmasses of the World**"), subtitle = md("The *top two* largest are presented") )
Large Landmasses of the World
The top two largest are presented
name size
Asia16988
Africa11506

A source note can be added to the table’sfooter through use of tab_source_note().It works in the same way as tab_header() (it also allowsfor Markdown inputs) except it can be called multiple times—eachinvocation results in the addition of a source note.

# Display the `islands_tbl` data with a heading and# two source notesgt_tbl <-  gt_tbl |> tab_source_note( source_note = "Source: The World Almanac and Book of Facts, 1975, page 406." ) |> tab_source_note( source_note = md("Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley.") )# Show the gt tablegt_tbl
Large Landmasses of the World
The top ten largest are presented
name size
Asia16988
Africa11506
North America9390
South America6795
Antarctica5500
Europe3745
Australia2968
Greenland840
New Guinea306
Borneo280
Source: The World Almanac and Book of Facts, 1975, page 406.
Reference: McNeil, D. R. (1977) Interactive Data Analysis. Wiley.

Footnotes live inside the Footer part and theirfootnote marks are attached to cell data. Footnotes are added withtab_footnote(). The helper functioncells_body() can be used with the locationargument to specify which data cells should be the target of thefootnote. cells_body() has the two argumentscolumns and rows. For each of these, we cansupply (1) a vector of colnames or rownames, (2) a vector of column/rowindices, (3) bare column names wrapped in c() or row labelswithin c(), or (4) a select helper function(starts_with(), ends_with(),contains(), matches(), one_of(),and everything()). For rows specifically, wecan use a conditional statement with column names as variables (e.g.,size > 15000).

Here is a simple example on how a footnotes can be added to a tablecell. Let’s add a footnote that references theNorth America and South America cells in thename column:

# Add footnotes (the same text) to two different# cell; data cells are targeted with `data_cells()`gt_tbl <-  gt_tbl |> tab_footnote( footnote = "The Americas.", locations = cells_body(columns = name, rows = 3:4) )# Show the gt tablegt_tbl
Large Landmasses of the World
The top ten largest are presented
name size
Asia16988
Africa11506
North America19390
South America16795
Antarctica5500
Europe3745
Australia2968
Greenland840
New Guinea306
Borneo280
Source: The World Almanac and Book of Facts, 1975, page 406.
Reference: McNeil, D. R. (1977) Interactive Data Analysis. Wiley.
1 The Americas.

Here is a slightly more complex example of adding footnotes that useexpressions in rows to help target cells in a column by theunderlying data in islands_tbl. First, a set ofdplyr statements obtains the name of the ‘island’ bylargest landmass. This is assigned to the largest objectand is used in the first tab_footnote() call that targetsthe cell in the size column that is next to aname value that is stored in largest (‘Asia’).The second tab_footnote() is similar except we aresupplying a conditional statement that gets the lowest population.

# Determine the row that contains the# largest landmass ('Asia')largest <-  islands_tbl |>  arrange(desc(size)) |> slice(1) |> pull(name)# Create two additional footnotes, using the# `columns` and `where` arguments of `data_cells()`gt_tbl <-  gt_tbl |> tab_footnote( footnote = md("The **largest** by area."), locations = cells_body( columns = size, rows = name == largest ) ) |> tab_footnote( footnote = "The lowest by area.", locations = cells_body( columns = size, rows = size == min(size) ) )# Show the gt tablegt_tbl
Large Landmasses of the World
The top ten largest are presented
name size
Asia116988
Africa11506
North America29390
South America26795
Antarctica5500
Europe3745
Australia2968
Greenland840
New Guinea306
Borneo3280
Source: The World Almanac and Book of Facts, 1975, page 406.
Reference: McNeil, D. R. (1977) Interactive Data Analysis. Wiley.
1 The largest by area.
2 The Americas.
3 The lowest by area.

We were able to supply the reference locations in the table by usingthe cells_body() helper function and supplying thenecessary targeting through the columns androws arguments. Other cells_*() functions havesimilar interfaces and they allow us to target cells in different partsof the table.

The Stub

The Stub is the area to the left in a table thatcontains row labels, and may contain row group labels,and summary labels. Those subparts can be grouped in a sequenceof row groups. The Stub Head provides alocation for a label that describes the Stub. TheStub is optional since there are cases where aStub wouldn’t be useful (e.g., the display tablespresented above were just fine without a Stub).

An easy way to generate a Stub part is by specifyinga stub column in the gt() function with therowname_col argument. This will signal togt that the named column should be used as the stub,making row labels. Let’s add a stub with ourislands_tbl dataset by modifying the call togt():

# Create a gt table showing ten of the# largest islands in the world; this# time with a stubgt_tbl <-  islands_tbl |> gt(rowname_col = "name")# Show the gt tablegt_tbl
size
Asia16988
Africa11506
North America9390
South America6795
Antarctica5500
Europe3745
Australia2968
Greenland840
New Guinea306
Borneo280

Notice that the landmass names are off the left in an unstriped area?That’s the stub. We can apply what’s known as astubhead label. This label can be added withtab_stubhead():

# Generate a simple table with a stub# and add a stubhead labelgt_tbl <-  gt_tbl |> tab_stubhead(label = "landmass")# Show the gt tablegt_tbl
landmass size
Asia16988
Africa11506
North America9390
South America6795
Antarctica5500
Europe3745
Australia2968
Greenland840
New Guinea306
Borneo280

A very important thing to note here is that the table now has onecolumn. Before, when there was no stub, two columnswere present (with column labels name andsize) but now column number 1 (the onlycolumn) is size.

To apply our table parts as before (up to and including thefootnotes) we use the following statements:

# Display the `islands_tbl` data with a stub,# a heading, source notes, and footnotesgt_tbl <-  gt_tbl |> tab_header( title = "Large Landmasses of the World", subtitle = "The top ten largest are presented" ) |> tab_source_note( source_note = "Source: The World Almanac and Book of Facts, 1975, page 406." ) |> tab_source_note( source_note = md("Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley.") ) |> tab_footnote( footnote = md("The **largest** by area."), locations = cells_body( columns = size, rows = largest ) ) |> tab_footnote( footnote = "The lowest by population.", locations = cells_body( columns = size, rows = contains("arc") ) )# Show the gt tablegt_tbl
Large Landmasses of the World
The top ten largest are presented
landmass size
Asia116988
Africa11506
North America9390
South America6795
Antarctica25500
Europe3745
Australia2968
Greenland840
New Guinea306
Borneo280
Source: The World Almanac and Book of Facts, 1975, page 406.
Reference: McNeil, D. R. (1977) Interactive Data Analysis. Wiley.
1 The largest by area.
2 The lowest by population.

Let’s incorporate row groups into the display table. This dividesrows into groups, creating row groups, and results in a displayof a row group labels right above the each group. This can beeasily done with a table containing row labels. We can make a newrow group with each tab_row_group() call. Theinputs are row group names in the label argument, and rowreferences in the rows argument. We can use any of thestrategies to reference rows as we did we footnotes (e.g., vectors ofnames/indices, select helpers, etc.).

Here we will create three row groups (with row group labelscontinent, country, andsubregion) to have a grouping of rows.

# Create three row groups with the# `tab_row_group()` functiongt_tbl <-  gt_tbl |>  tab_row_group( label = "continent", rows = 1:6 ) |> tab_row_group( label = "country", rows = c("Australia", "Greenland") ) |> tab_row_group( label = "subregion", rows = c("New Guinea", "Borneo") )# Show the gt tablegt_tbl
Large Landmasses of the World
The top ten largest are presented
landmass size
subregion
New Guinea306
Borneo280
country
Australia2968
Greenland840
continent
Asia116988
Africa11506
North America9390
South America6795
Antarctica25500
Europe3745
Source: The World Almanac and Book of Facts, 1975, page 406.
Reference: McNeil, D. R. (1977) Interactive Data Analysis. Wiley.
1 The largest by area.
2 The lowest by population.

Three row groups have been made since there are three uniquecategories under groupname. Across the top of each rowgroup is the row group label contained in a separate row(these cut across the field and they contain nothing but the rowgroup label). A rearrangement of rows is carried out to ensure eachof the rows is collected within the appropriate row groups.

Having groups of rows in row groups is a great way topresent information. Including data summaries particular to each groupis a natural extension of this idea. This process of adding summary rowswith summary labels is covered in a separate article(Creating Summary Lines).

Another way to make row groups is to have a column of group namespresent in the input data table. For our above example withislands_tbl, having a groupname column withthe categories continent, country, andsubregion in the appropriate rows would produce row groupswhen using the gt() function’s groupname_colargument (e.g.,gt(islands_tbl, rowname_col = "name", groupname_col = "groupname") |> ...).Then, there would be no need to use tab_row_group(). Thisstrategy of supplying group names in a column can sometimes beadvantageous since we can rely on functions such as those available indplyr to generate the categories (e.g., usingcase_when() or if_else()).

The Column Labels

The table’s Column Labels part contains, at aminimum, columns and their column labels. The last example hada single column: size. Just as in theStub, we can create groupings called spannercolumns that encompass one or more columns.

To better demonstrate how Column Labels work and aredisplayed, let’s use an input data table with more columns. In thiscase, that input table will be airquality. It has thefollowing columns:

  • Ozone: mean ground-level ozone in parts per billion byvolume (ppbV), measured between 13:00 and 15:00
  • Solar.R: solar radiation in Langley units(cal/m2), measured between 08:00 and noon
  • Wind: mean wind speed in miles per hour (mph)
  • Temp: maximum daily air temperature in degreesFahrenheit (°F)
  • Month, Day: the numeric month and day ofmonth for the record

We know that all measurements took place in 1973, so ayear column will be added to the dataset before it ispassed to gt().

Let’s organize the time information under a Timespanner column label, and put the other columns under aMeasurement spanner column label. We can do thiswith tab_spanner().

# Modify the `airquality` dataset by adding the year# of the measurements (1973) and limiting to 10 rowsairquality_m <-  airquality |> mutate(Year = 1973L) |> slice(1:10) # Create a display table using the `airquality`# dataset; arrange columns into groupsgt_tbl <-  gt(airquality_m) |> tab_header( title = "New York Air Quality Measurements", subtitle = "Daily measurements in New York City (May 1-10, 1973)" ) |> tab_spanner( label = "Time", columns = c(Year, Month, Day) ) |> tab_spanner( label = "Measurement", columns = c(Ozone, Solar.R, Wind, Temp) )# Show the gt tablegt_tbl
New York Air Quality Measurements
Daily measurements in New York City (May 1-10, 1973)
Measurement Time
Ozone Solar.R Wind Temp Year Month Day
411907.467197351
361188.072197352
1214912.674197353
1831311.562197354
NANA14.356197355
28NA14.966197356
232998.665197357
199913.859197358
81920.161197359
NA1948.6691973510

We can do two more things to make this presentable:

  • move the Time columns to the beginning of the series(using cols_move_to_start())
  • customize the column labels so that they are more descriptive (usingcols_label())

Let’s do both of these things in the next example.

# Move the time-based columns to the start of# the column series; modify the column labels of# the measurement-based columnsgt_tbl <-  gt_tbl |> cols_move_to_start( columns = c(Year, Month, Day) ) |> cols_label( Ozone = html("Ozone,<br>ppbV"), Solar.R = html("Solar R.,<br>cal/m<sup>2</sup>"), Wind = html("Wind,<br>mph"), Temp = html("Temp,<br>&deg;F") )# Show the gt tablegt_tbl
New York Air Quality Measurements
Daily measurements in New York City (May 1-10, 1973)
Time Measurement
Year Month Day Ozone,
ppbV
Solar R.,
cal/m2
Wind,
mph
Temp,
°F
197351411907.467
197352361188.072
1973531214912.674
1973541831311.562
197355NANA14.356
19735628NA14.966
197357232998.665
197358199913.859
19735981920.161
1973510NA1948.669

Note that even though columns were moved usingcols_move_to_start(), the spanner column labelsstill spanned above the correct column labels. There are anumber of functions that gt provides to move columns,including cols_move(), cols_move_to_end();there’s even a function to hide columns: cols_hide().

Multiple columns can be renamed in a single use ofcols_label(). Further to this, the helper functionsmd() and html() can be used to create columnlabels with additional styling. In the above example, we provided columnlabels as HTML so that we can insert linebreaks with<br>, insert a superscripted 2 (with<sup>2</sup>), and insert a degree symbol as anHTML entity (&deg;).

Introduction to Creating gt Tables (2024)

References

Top Articles
Gratis Bingokaart- en Bordsjablonen: Aanpassen en Afdrukken
Bingo Card Generator - Make Custom Printable Bingo Cards
'That's Hilarious': Ahsoka's Ezra Bridger Actor Reveals Surprising True-To-Life Detail Behind Sabine Reunion Scene
Jimmy Johns Delivery Hours
Tweaker Configuration
Anonib Altoona Pa
Q-global Web-based Administration, Scoring, and Reporting
"Rainbow Family" will im Harz bleiben: Hippie-Camp bis Anfang September geplant
Olive Onyx Amora
Tinyzonetv.to Unblocked
303-615-0055
Fisher-Cheney Funeral Home Obituaries
My Big Fat Greek Wedding 3 Showtimes Near Regal Ukiah
O'reilly's Iron Mountain Michigan
Albany Want Ad Digest
Elven Signet Osrs
Jinx Bl Chapter 26
Gina's Pizza Port Charlotte Fl
Days Till Dec 6
Charm City Kings 123Movies
Odawa Hypixel
Diablo 3 Legendary Reforge
Scrap Metal Prices in Indiana, Pennsylvania Scrap Price Index,United States Scrap Yards
Spring Tx Radar
Atlanticbb Message Center
Worldfree4U In
No hard feelings: cómo decir "no" en inglés educadamente y sin herir sensibilidades
Mudfin Village Questline
Walmart Front Door Wreaths
House Party 2023 Showtimes Near Mjr Chesterfield
Lohud Rockland Obituaries
The Little Mermaid 2023 Showtimes Near Marcus South Pointe Cinema
Natick Mall Directory Map
Krua Thai In Ravenna
Son Blackmailing Mother
Briggs And Stratton 125Cc Lawn Mower
Craigslist Cars Merced Ca
South Carolina Craigslist Motorcycles
marie claire Australia January 2016 Robyn Lawley, Rachel Taylor, Sarah Snook • EUR 11,50
Hyundai Elantra - modele, dane, silniki, testy
Egg Inc Ultimate Walkthrough & Game Guide - Talk Android
Blow Dry Bar Boynton Beach
How To Buy Taylor Swift Tickets By Navigating Ticketek's Stress-Inducing System
Neo Geo Bios Raspberry Pi 3
Jefferey Dahmer Autopsy Photos
Cibo Tx International Kitchen Schertz Menu
Christina Cox Measurements
Agurahl The Butcher Wow
Fraction Button On Ti-84 Plus Ce
Yahoo Sports Pga Leaderboard
Liberty 1098-T
Never Would Have Made It Movie 123Movies
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 6237

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.