The text_case_when() function

Use a portion of the metro dataset to create a gt table. We’ll use text_case_when() to supply pairs of predicate statements and replacement text. For the connect_rer column, we will perform a count of pattern matches with stringr::str_count() and determine which cells have 1, 2, or 3 matched patterns. For each of these cases, descriptive replacement text is provided. Here, we use a .default value to replace the non-matched cases with an empty string (""). Finally, we use cols_label() to modify the labels of the three columns.

metro |>
  dplyr::arrange(desc(passengers)) |>
  dplyr::select(name, lines, connect_rer) |>
  dplyr::slice_head(n = 10) |>
  gt() |>
  text_case_when(
    stringr::str_count(x, pattern = "[ABCDE]") == 1 ~ "One connection.",
    stringr::str_count(x, pattern = "[ABCDE]") == 2 ~ "Two connections.",
    stringr::str_count(x, pattern = "[ABCDE]") == 3 ~ "Three connections.",
    .default = "", .locations = cells_body(columns = connect_rer)
  ) |>
  cols_label(
    name = "Station",
    lines = "Lines Serviced",
    connect_rer = "RER Connections"
  )
Station Lines Serviced RER Connections
Gare du Nord 4, 5 Three connections.
Saint-Lazare 3, 12, 13, 14 One connection.
Gare de Lyon 1, 14 Two connections.
Montparnasse—Bienvenüe 4, 6, 12, 13
Gare de l'Est 4, 5, 7
Bibliothèque François Mitterrand 14 One connection.
République 3, 5, 8, 9, 11
Les Halles 4 Three connections.
La Défense 1 Two connections.
Châtelet 1, 4, 7, 11, 14 Three connections.