jthomasmock / gtExtras

A Collection of Helper Functions for the gt Package.
https://jthomasmock.github.io/gtExtras/
Other
193 stars 26 forks source link

auto tab_spanner #84

Closed cvaldezerea closed 1 year ago

cvaldezerea commented 1 year ago
auto_span <- function(gtable) {
  names_gtable <- names(gtable$`_data`)
  names_gtable_ <- tibble::tibble(names = names_gtable) %>%
    dplyr::mutate(
     label = stringr::str_extract(string = names,pattern = ".*?\\."),
     name_new = stringr::str_remove(string = names,pattern =".*?\\."),
     label = stringr::str_remove(string = label,pattern = "\\."),
     cols = dplyr::row_number()
    ) %>%
    dplyr::mutate(
      label = toupper(stringr::str_replace_all(string = label,pattern = "_",replacement = " ")),
      name_new = toupper(stringr::str_replace_all(string = name_new,pattern = "_",replacement = " "))
    )
  label_seq <- as.character(na.omit(unique(names_gtable_$label)))
  new_names <- setNames(names_gtable_$name_new, names_gtable_$names)

  if(length(label_seq) > 0){
    for(i in label_seq){
      gtable <- gtable %>%
        gt::tab_spanner(
          label = i,
          columns = as.integer(na.omit(names_gtable_$cols[names_gtable_$label == i]))
        )
    }
    gtable <- gtable %>%
      gt::cols_label(!!!new_names)
  }
  return(gtable)
}
jthomasmock commented 1 year ago

Hi @cvaldezerea can you provide some context and/or need here on the feature request? Thanks!

cvaldezerea commented 1 year ago

Ho @jthomasmock ,

this function takes this

image

into this

image

something like that is very useful, i made this today but i believe a function like this can be really helpful

jthomasmock commented 1 year ago

Thanks Cristian - this is a neat idea, but I think a bit too specific to generalize for this package.