gt Tables Exercises in R: 15 Practice Problems
Fifteen practice problems on gt tables: formatting numbers, headers, footnotes, colors, summary rows. Hidden solutions.
RRun this once before any exercise
library(gt)
library(dplyr)
library(scales)
Exercise 1: Basic gt
Difficulty: Beginner.
Show solution
RInteractive R
head(mtcars, 5) |> gt()
Exercise 2: Title and subtitle
Difficulty: Beginner.
Show solution
RInteractive R
head(mtcars, 5) |> gt() |>
tab_header(title = "Cars", subtitle = "Top 5")
Exercise 3: Format numeric column
Difficulty: Intermediate.
Show solution
RInteractive R
head(mtcars, 5) |> gt() |> fmt_number(mpg, decimals = 1)
Exercise 4: Format as currency
Difficulty: Intermediate.
Show solution
RInteractive R
diamonds |> head(5) |> gt() |> fmt_currency(price)
Exercise 5: Format percent
Difficulty: Intermediate.
Show solution
RInteractive R
tibble(rate = c(0.05, 0.10, 0.25)) |> gt() |> fmt_percent(rate)
Exercise 6: Color cells by value
Difficulty: Advanced.
Show solution
RInteractive R
head(mtcars, 5) |> gt() |>
data_color(columns = mpg,
colors = scales::col_numeric("Blues", domain = NULL))
Exercise 7: Footnote
Difficulty: Intermediate.
Show solution
RInteractive R
head(mtcars, 3) |> gt() |>
tab_footnote(footnote = "Source: mtcars", locations = cells_title("title"))
Exercise 8: Column groups (spanners)
Difficulty: Advanced.
Show solution
RInteractive R
head(mtcars, 3) |> gt() |>
tab_spanner(label = "Engine", columns = c(cyl, disp, hp))
Exercise 9: Hide a column
Difficulty: Intermediate.
Show solution
RInteractive R
head(mtcars, 3) |> gt() |> cols_hide(carb)
Exercise 10: Rename columns
Difficulty: Beginner.
Show solution
RInteractive R
head(mtcars, 3) |> gt() |> cols_label(mpg = "MPG", cyl = "Cyl")
Exercise 11: Summary row (grouped)
Difficulty: Advanced.
Show solution
RInteractive R
mtcars |> head(10) |> group_by(cyl) |> gt() |>
summary_rows(groups = TRUE, columns = mpg, fns = list(mean = ~ mean(.x)))
Exercise 12: Add row groups
Difficulty: Advanced.
Show solution
RInteractive R
mtcars |> head(10) |> mutate(grp = ifelse(mpg > 20, "Hi","Lo")) |>
gt(rowname_col = NULL, groupname_col = "grp")
Exercise 13: tab_style bold
Difficulty: Advanced.
Show solution
RInteractive R
head(mtcars, 5) |> gt() |>
tab_style(style = cell_text(weight = "bold"),
locations = cells_body(columns = mpg, rows = mpg > 25))
Exercise 14: Save to HTML/PNG
Difficulty: Intermediate.
Show solution
RInteractive R
g <- head(mtcars, 5) |> gt()
gtsave(g, "out.html")
Exercise 15: Compact theme
Difficulty: Intermediate.
Show solution
RInteractive R
head(mtcars, 5) |> gt() |> opt_table_lines("none")
What to do next
- Data-Visualization-Exercises (shipped), broader viz.
- R-Markdown-Exercises (shipped), tables in reports.