Search code examples
rdplyrtibblegt

R gt table formatting: How can I take my long gt table and make it wide?


I would like to take a gt() table and transform it to a "wide" format instead of a "long" format by group level. So for, as an example using the iris data set:

library(dplyr)  
library(gt)  
iris %>%   
group_by(Species) %>%   
slice_max(Sepal.Length, n=5) %>%  
group_by(Species) %>%  
gt() 

This produces:

Standard gt output

However, what I want to produce is the following:

Desired gt output

Is there a way to do this?


Solution

  • We can do this with a combination of data reshaping and gt formatting functions. I've also reformatted the column names to remove periods and put them in title case.

    library(tidyverse)  
    library(gt)  
    
    iris %>%   
      group_by(Species) %>%   
      slice_max(Sepal.Length, n=5) %>%   
      group_by(Species) %>% 
      mutate(row=row_number()) %>% 
      pivot_longer(-c(Species, row)) %>%
      mutate(Species = str_to_title(Species),
             name = gsub("\\.", " ", name)) %>% 
      pivot_wider(names_from=c(Species, name), values_from=value) %>% 
      select(-row) %>% 
      gt() %>% 
      tab_spanner_delim(
          delim="_"
      ) %>% 
      fmt_missing(
        columns=everything(),
        missing_text=""
      )
    

    enter image description here