The text_transform() function

Use sp500 to create a gt table. Transform the text in the date column using a function supplied to text_transform() (via the fn argument). Note that the x in the fn = function (x) part consists entirely of ISO 8601 date strings (which are acceptable as input to the vec_fmt_date() and vec_fmt_datetime() functions).

sp500 |>
  dplyr::slice_head(n = 10) |>
  dplyr::select(date, open, close) |>
  dplyr::arrange(-dplyr::row_number()) |>
  gt() |>
  fmt_currency() |>
  text_transform(
    fn = function(x) {
      paste0(
        "<strong>",
        vec_fmt_date(x, date_style = "m_day_year"),
        "</strong>",
        "&mdash;W",
        vec_fmt_datetime(x, format = "w")
      )
    },
    locations = cells_body(columns = date)
  ) |>
  cols_label(
    date = "Date and Week",
    open = "Opening Price",
    close = "Closing Price"
  )
Date and Week Opening Price Closing Price
Dec 17, 2015—W51 $2,073.76 $2,041.89
Dec 18, 2015—W51 $2,040.81 $2,005.55
Dec 21, 2015—W52 $2,010.27 $2,021.15
Dec 22, 2015—W52 $2,023.15 $2,038.97
Dec 23, 2015—W52 $2,042.20 $2,064.29
Dec 24, 2015—W52 $2,063.52 $2,060.99
Dec 28, 2015—W53 $2,057.77 $2,056.50
Dec 29, 2015—W53 $2,060.54 $2,078.36
Dec 30, 2015—W53 $2,077.34 $2,063.36
Dec 31, 2015—W53 $2,060.59 $2,043.94

Use gtcars to create a gt table. First, the numeric values in the n column are formatted as spelled-out numbers with fmt_spelled_num(). The output values are indeed spelled out but exclusively with lowercase letters. We actually want these words to begin with a capital letter and end with a period. To make this possible, the text_transform() function will be used since it can modify already-formatted text. Through the fn argument, we provide a custom function that uses R’s toTitleCase() operating on x (the numbers-as-text strings) within a paste0() so that a period can be properly placed.

gtcars |>
  dplyr::select(mfr, ctry_origin) |>
  dplyr::filter(ctry_origin %in% c("Germany", "Italy", "Japan")) |>
  dplyr::group_by(mfr, ctry_origin) |>
  dplyr::count() |>
  dplyr::ungroup() |>
  dplyr::arrange(ctry_origin, desc(n)) |>
  gt(rowname_col = "mfr", groupname_col = "ctry_origin") |>
  cols_label(n = "No. of Entries") |>
  tab_stub_indent(rows = everything(), indent = 2) |>
  cols_align(align = "center", columns = n) |>
  fmt_spelled_num() |>
  text_transform(
    fn = function(x) {
      paste0(tools::toTitleCase(x), ".")
    },
    locations = cells_body(columns = n)
  )
No. of Entries
Germany
Audi Five.
BMW Five.
Porsche Four.
Mercedes-Benz Two.
Italy
Ferrari Nine.
Lamborghini Three.
Maserati Three.
Japan
Acura One.
Nissan One.