Link Search Menu Expand Document

Building Custom Tables

Sometimes you need to create a table that doesn’t fit neatly into any of the other categories of table shown the Tables page.

Keep in Mind

  • Graphs are sometimes a more effective way to convey information.

Also Consider

  • Check the Tables page to see if any of those approaches will work for your application.

Implementations

R

There are lots of ways to create custom tables, I am using RStudio’s gt because it is easy to use and gives me a lot of control over the table elements. It has many more options than I am demonstrating so be sure to look at their documentation.

# Install gt if necessary
# install.packages('gt')
library(gt)

# I'm also loading magrittr so I can use the %>% pipe
library(magrittr)

# you data will need to be in a data.frame or tibble object
# for this example I'll use the generic dataset mtcars
# which I'm truncating to make the final table easier to see
input_df = head(mtcars, 6)
input_df = input_df[, 1:5]


# create the table including the data.frame rownames
Ex_table = gt(input_df, rownames_to_stub = TRUE)


# add title, subtitle, and source note
Ex_table = Ex_table %>%
  tab_header(
    title = md("**Title in Bold Text**"),
    subtitle = "subtitle"
  ) %>%
  tab_source_note("Data from mtcars")


# add groupings to rows
Ex_table = Ex_table %>%
  tab_row_group(
    label = "4 Cylinder",
    rows = cyl == 4
  ) %>%
  tab_row_group(
    label = "6 Cylinder",
    rows = cyl == 6
  ) %>%
  tab_row_group(
    label = "8 Cylinder",
    rows = cyl == 8
  ) 
  

This produces:

Title in Bold Text
subtitle
mpg cyl disp hp drat
8 Cylinder
Hornet Sportabout 18.7 8 360 175 3.15
6 Cylinder
Mazda RX4 21.0 6 160 110 3.90
Mazda RX4 Wag 21.0 6 160 110 3.90
Hornet 4 Drive 21.4 6 258 110 3.08
Valiant 18.1 6 225 105 2.76
4 Cylinder
Datsun 710 22.8 4 108 93 3.85
Data from mtcars

Citation for gt:
Iannone R, Cheng J, Schloerke B (2022). gt: Easily Create Presentation-Ready Display Tables. https://gt.rstudio.com/, https://github.com/rstudio/gt.