rstudio / gt

Easily generate information-rich, publication-quality tables from R
https://gt.rstudio.com
Other
1.98k stars 199 forks source link

New function `tab_spanners_label_with` and levels-param for `cells_column_spanners` #1628

Open obsaditelnost opened 4 months ago

obsaditelnost commented 4 months ago

Prework

Proposal

A new function tab_spanners_label_with to change the spanner labels in a consistent shortcut way, comparable to cols_label_with().

With some data pre-processing in most cases there is not really a need for this function unless the style is dynamic and should be centralised in the gt-call. In some other cases such a function would be very useful, especially when spanners are created dynamically (either by a loop or tab_spanner_delim). Due to the way in which spanners are created by the user, a cols_label() alternative for spanners would be less useful in my eyes.

text_transform with the location (cells_column_spanners) could do something similar to the proposed tab_spanners_label_with but with some current inconsitencies (see #1433 ) and some more syntax to use, tab_spanners_label_with might be a easier way to change labels - especially with a "levels" argument to the location-helper (that is not yet available)

_@rich-iannone If there are no reasons against such a function and the additional levels-parameter of cells_column_spanners, I might look into the implementation of it_

see also

1551 (the tab_spanners_label_with approach might be a better alternative to the suggestion in that issue because these fmt-functions are suited to the table contents* due to their inherent parameters)

Example

library(gt)
library(htmltools)

x <- iris
names(x) <- c(
  "Sepal<br>under.Length",
  "Sepal<br>under.Width",
  "Petal<br>under.Length",
  "Petal<br>under.Width",
  "Species"
)

gt(x) |>
  tab_spanner_delim(delim = ".") |>
  gt::tab_spanners_label_with(fn = gt::md, spanners = everything()) |>
  gt::tab_spanner("Lengths and Widths", columns = tidyselect::matches("(Length)|(Width)")) |>
  gt::tab_spanners_label_with(
    fn = toupper,
    spanners = "Lengths and Widths"
  ) |>
  gt::tab_spanners_label_with(
    fn = function(x) htmltools::doRenderTags(htmltools::tags$u(htmltools::HTML(x))),
    spanners = everything(),
    levels = c(1)
  ) %>%
  tab_style(
    style = cell_text(color = "red"),
    locations = cells_column_spanners(
      spanners = tidyselect::matches("(Lengths)|(Sepal)", ignore.case = TRUE),
      # restrict red color to first level even though location helper would match
      # level 2 as well
      levels = 1
    )
  )

image

rich-iannone commented 3 months ago

Sorry for taking so long to reply. I think starting with an enhancement to cells_column_spanners() is a good idea. Please go ahead with a PR for that!

As far as the other part of the proposal, I agree it’s needed but we should iterate a little bit more on the API design there.