Skip to content

Instantly share code, notes, and snippets.

@jmclawson
Last active September 4, 2023 16:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmclawson/6852c14023d7d9b7e91bbcfa419adeb8 to your computer and use it in GitHub Desktop.
Save jmclawson/6852c14023d7d9b7e91bbcfa419adeb8 to your computer and use it in GitHub Desktop.
something like "collapse rows" for gt
collapse_rows <- function(df_g, col, lookleft = TRUE){
col_num <- grep(deparse(substitute(col)), colnames(df_g$`_data`))
collapse_style <- css(visibility = "hidden",
border_top = "0px")
test_rows <- function(x) ifelse(is.na(x == lag(x)), FALSE, x == lag(x))
if(col_num > 1 & lookleft) {
col_left <- as.name(colnames(df_g$`_data`)[col_num - 1])
df_g |>
tab_style(
style = collapse_style,
locations = cells_body(columns = {{ col }},
rows = test_rows({{ col }}) & test_rows({{ col_left }})))
} else {
df_g |>
tab_style(
style = collapse_style,
locations = cells_body(columns = {{ col }},
rows = test_rows({{ col }})))
}
}
@jmclawson
Copy link
Author

Example of use:

penguins |>  
    summarize(avg_weight = mean(body_mass_g),
              .by = c(species, island, sex)) |> 
    mutate(across(1:3, as.character)) |> 
    drop_na() |> 
    gt() |> 
    collapse_rows(island) |> 
    collapse_rows(species) 

Results in this:

Screenshot 2023-08-21 at 10 48 07 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment