The fmt_image() function

Using a small portion of metro dataset, let’s create a gt table. We will only include a few columns and rows from that table. The lines and connect_rer columns have comma-separated listings of numbers/letters (corresponding to lines served at each station). We have a directory of SVG graphics for all of these lines within the package (the path for the directory containing the images can be accessed via system.file("metro_svg", package = "gt")), and the filenames roughly correspond to the data in those two columns. fmt_image() can be used with these inputs since the path and file_pattern arguments allow us to compose complete and valid file locations. What you get from all of this are sequences of images in the table cells, taken from the referenced graphics files on disk.

metro |>
  dplyr::select(name, caption, lines, connect_rer) |>
  dplyr::slice_head(n = 10) |>
  gt() |>
  cols_merge(
    columns = c(name, caption),
    pattern = "{1}<< ({2})>>"
  ) |>
  text_replace(
    locations = cells_body(columns = name),
    pattern = "\\((.*?)\\)",
    replacement = "<br>(<em>\\1</em>)"
  ) |>
  sub_missing(columns = connect_rer, missing_text = "") |>
  fmt_image(
    columns = lines,
    path = system.file("metro_svg", package = "gt"),
    file_pattern = "metro_{x}.svg"
  ) |>
  fmt_image(
    columns = connect_rer,
    path = system.file("metro_svg", package = "gt"),
    file_pattern = "rer_{x}.svg"
  ) |>
  cols_label(
    name = "Station",
    lines = "Lines",
    connect_rer = "RER"
  ) |>
  cols_align(align = "left") |>
  tab_style(
    style = cell_borders(
      sides = c("left", "right"),
      weight = px(1),
      color = "gray85"
    ),
    locations = cells_body(columns = lines)
  ) |>
  opt_stylize(style = 6, color = "blue") |>
  opt_all_caps() |>
  opt_horizontal_padding(scale = 1.75)
Station Lines RER
Argentine
Bastille
Bérault
Champs-Élysées—Clemenceau
(Grand Palais)

Charles de Gaulle—Étoile
Château de Vincennes
Châtelet
Concorde
Esplanade de La Défense
Franklin D. Roosevelt