Search code examples
rgt

Add a second `groupname_col` in `gt` table without concatenating the column values


I love gt's ability to separate row groups into columns, but I want to have TWO row groups as columns, not one column with two groups concatenated, which is the default. For example:

library(gt)

gtcars %>%
  group_by(mfr, year) %>%
  gt(row_group_as_column = TRUE)

This gives us a gt table that looks like this, with the Make and the year concatenated into one column. Is there a way to have two separate grouping columns, one for the mfr and one for the year?

enter image description here


Solution

  • library(gt)
    library(dplyr)
    
    gtcars %>%
      mutate(mfr = factor(mfr, levels = unique(mfr))) %>%  ## keep the original order
      arrange(mfr, year) %>%   
      mutate(year = ifelse(row_number() == 1, as.character(year), ""),
             .by = c(mfr, year)) %>% 
      mutate(mfr = ifelse(row_number() == 1, as.character(mfr), ""),
             .by = mfr) %>% 
      select(mfr, year, everything()) %>% 
      gt()