I know one can split a gt() table into groups by factor level, but can these groups be further sub-divided into sub-groups? For example, using this mock data:
data <- data.frame(
rowname = rep(c("Row1", "Row2", "Row3", "Row4"), times = 2),
Season = rep(c("Spring", "Fall"), each = 4),
Value = c(10, 20, 30, 40, 15, 25, 35, 45)
)
And this table...
library(gt)
library(dplyr)
data %>%
gt(rowname_col = "rowname", # Specify the column to use for row names
groupname_col = "Season") %>% # Specify the column to use for grouping
tab_header(
title = "Grouped Table with Custom Row Names"
)
Can I split the groups for each level in "Season" into two parts? As in, "Spring" has 2 parts: one part for when the row names = "Row1" and "Row2" specifically, and a second for the other values. I tried using this code below with tab_row_group, but it overrides the first grouping structure (Season) and just creates a 3rd group level.
Does the following approach work for you? It involves creating a second grouping variable, which I've called season_part, grouping the data by both Season and season_part before passing to gt().
library(dplyr)
library(gt)
data <- data.frame(
rowname = rep(c("Row1", "Row2", "Row3", "Row4"), times = 2),
Season = rep(c("Spring", "Fall"), each = 4),
Value = c(10, 20, 30, 40, 15, 25, 35, 45)
)
data |>
as_tibble() |>
mutate(
season_part = case_match(
rowname,
c('Row1', 'Row2') ~ 'Part 1',
.default = 'Part 2'
)
) |>
group_by(Season, season_part) |>
gt() |>
tab_header(title = 'Grouped Table with Custom Row Names')