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

1

6

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?

Haleakala answered 5/2, 2021 at 22:11 Comment(2)
Are you placing the output into shiny or a markdown file? There may be a work around by creating two tables that you place side-by-side in columns in your output.Garmaise
@SusanSwitzer I was planning on putting the table in a powerpoint slide as an image.Haleakala
R
5

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

Rodrigorodrigue answered 5/2, 2021 at 22:37 Comment(1)
Is there a way to draw vertical line between these different spanner groups?Acarus

© 2022 - 2024 — McMap. All rights reserved.