GT tables

In my job, I make tables all the time

I recently stumbled upon the {gt} package and whoa… these are some great looking tables! You can check out the documentation here

Even better, they are easy to append to any dplyr pipeline…


Step 1: Load {gt} and {dplyr}

library(gt)
library(dplyr)

 
Step 2:

  • Create a frequency table with mtcars, grouped by number of cylinders.
  • Dplyr is quick and simple to use, but the console output is not so easy on the eyes…
mtcars %>%
  group_by(cyl) %>%
  summarize(N = n()) %>%
  mutate(Frequency = N/sum(N),
         Frequency = round(Frequency, 2))
## # A tibble: 3 x 3
##     cyl     N Frequency
##   <dbl> <int>     <dbl>
## 1     4    11      0.34
## 2     6     7      0.22
## 3     8    14      0.44

 
Step 3: Lets add some {gt} magic…getting better

mtcars %>%
    group_by(cyl) %>%
    summarize(N = n()) %>%
    mutate(Frequency = N/sum(N),
           Frequency = round(Frequency, 2)) %>%
    gt() 
cyl N Frequency
4 11 0.34
6 7 0.22
8 14 0.44

 
Step 4: Ok, now adding some bells and whistles, we can really make this table shine…

mtcars %>%
  group_by(cyl) %>%
  summarize(N = n()) %>%
    mutate(Frequency = N/sum(N),
           Frequency = round(Frequency, 2)) %>%
    gt(rowname_col = "cyl") %>%
    tab_stubhead(label = "Cylinders") %>%
  tab_header(
    title = md("Table 1: MTCARS cyl table"),
    subtitle = md("Made with {gt} package")
  ) %>% 
  tab_footnote(
    footnote = "Added a footnote",
    locations = cells_data(
      columns = vars(N), 
      row = 1 #add to the row with 4 cylinders
    )
  ) %>% 
  tab_source_note(
    source_note = "Example 1: Add a source note here"
  ) %>%
  tab_source_note(
    source_note = "Example 2: Add another note/reference here!"
  ) %>%
  cols_align(
    align = "center", 
    columns = vars(N, Frequency)
  ) %>%
  tab_options(heading.background.color = "#aa6f73", 
              heading.border.bottom.color = "black", 
              heading.title.font.size = 24, 
              heading.subtitle.font.size = 22, 
              table.width = 370, 
              table.font.size = 18, 
              column_labels.font.size = 20, 
              row.striping.include_stub = TRUE,
              row.striping.include_table_body = TRUE)
Table 1: MTCARS cyl table
Made with {gt} package
Cylinders N Frequency
4 111 0.34
6 7 0.22
8 14 0.44
Example 1: Add a source note here
Example 2: Add another note/reference here!

1 Added a footnote

 
Done!
Simply calling gt() creates the table, then add a few parameters to control the style/font size etc…Voila! You have a fancy gt Table…

Avatar
Eric Bergh, MD
Fetal Intervention

My research interests include fetal medicine, ultrasound, high-risk pregnancy