Search code examples
rr-markdowngt

Arrange gt tables side by side or in a grid or table of tables


I'd like to generate a set of gt table objects in a grid or side-by-side. For example, the code below uses the group_by argument to vertically separate them. But what if I wanted them separated side-by-side?

mtcars2 <-
  mtcars %>% 
  mutate(good_mpg = ifelse(mpg > 20, "Good mileage", "Bad mileage"), 
         car_name = row.names(.)) 

mtcars2 %>% 
  group_by(good_mpg) %>% 
  slice_max(order_by = hp, n=5) %>% 
  arrange(hp) %>% 
  select(car_name, hp) %>% 
  gt() %>% 
  data_color(columns = c("hp"), 
             colors = col_numeric(palette = "Blues", 
                                  domain = c(0, 400)))

table with vertical group_by


Solution

  • @Daniel, thank you for sharing this! This can come in handy.

    To make the code a little bit more compact you could use group_map (or do) to generate the two tables within the dplyr workflow, then join them as you did:

    library(dplyr)
    library(gt)
    library(scales)
    
    hp_table <- function(x){
        gt(x) %>% 
            data_color(columns="hp", 
                       colors=col_numeric(palette="Blues", c(0, 400))) %>% 
            tab_options(column_labels.hidden = TRUE) %>% 
            as_raw_html()
    }
    
    mtcars %>% 
        mutate(good_mpg = ifelse(mpg > 20, "Good mileage", "Bad mileage"), 
               car_name = row.names(.))  %>% 
        arrange(hp) %>% 
        group_by(relevel(factor(good_mpg), "Good mileage")) %>% 
        slice_head(n=5) %>% 
        select(car_name, hp) %>%
        group_map(~ hp_table(.x)) %>% 
        data.frame(.) %>% 
        setNames(., c("High mileage", "Low mileage")) %>% 
        gt() %>% 
        fmt_markdown(columns = TRUE)