The cols_merge() function

Use a subset of the sp500 dataset to create a gt table. Use the cols_merge() function to merge the open & close columns together, and, the low & high columns (putting an em dash between both). Relabel the columns with cols_label().

sp500 |>
  dplyr::slice(50:55) |>
  dplyr::select(-volume, -adj_close) |>
  gt() |>
  cols_merge(
    columns = c(open, close),
    pattern = "{1}—{2}"
  ) |>
  cols_merge(
    columns = c(low, high),
    pattern = "{1}—{2}"
  ) |>
  cols_label(
    open = "open/close",
    low = "low/high"
  )
date open/close low/high
2015-10-21 2033.47—2018.94 2017.22—2037.97
2015-10-20 2033.13—2030.77 2026.61—2039.12
2015-10-19 2031.73—2033.66 2022.31—2034.45
2015-10-16 2024.37—2033.11 2020.46—2033.54
2015-10-15 1996.47—2023.86 1996.47—2024.15
2015-10-14 2003.66—1994.24 1990.73—2009.56

Use a portion of gtcars to create a gt table. Use the cols_merge() function to merge the trq & trq_rpm columns together, and, the mpg_c & mpg_h columns. Given the presence of NA values, we can use patterns that drop parts of the output text whenever missing values are encountered.

gtcars |>
  dplyr::filter(year == 2017) |>
  dplyr::select(mfr, model, starts_with(c("trq", "mpg"))) |>
  gt() |>
  fmt_integer(columns = trq_rpm) |>
  cols_merge(
    columns = starts_with("trq"),
    pattern = "{1}<< ({2} rpm)>>"
  ) |>
  cols_merge(
    columns = starts_with("mpg"),
    pattern = "<<{1} city<</{2} hwy>>>>"
  ) |>
  cols_label(
    mfr = "Manufacturer",
    model = "Car Model",
    trq = "Torque",
    mpg_c = "MPG"
  )
Manufacturer Car Model Torque MPG
Ford GT 550 (5,900 rpm) 11 city/18 hwy
Ferrari GTC4Lusso 514 (5,750 rpm) 12 city/17 hwy
Acura NSX 476 (2,000 rpm) 21 city/22 hwy
Aston Martin DB11 516 (1,500 rpm) 15 city/21 hwy
Dodge Viper 600 (5,000 rpm) 12 city/19 hwy
Lotus Evora 302 (3,500 rpm) 16 city/24 hwy
Tesla Model S 243
Porsche 718 Boxster 280 (1,950 rpm) 21 city/28 hwy
Porsche 718 Cayman 280 (1,950 rpm) 20 city/29 hwy