并排或在网格中排列 gt tables 或 table of tables

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

我想在网格中或并排生成一组 gt table 个对象。例如,下面的代码使用 group_by 参数来 垂直 分隔它们。但是如果我想让它们并排分开呢?

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 中使用 as_raw_html() 并在顶层 table 中使用 fmt_markdown(columns = TRUE) 来做到这一点。


hp_table <- function(x){
  gt(x) %>% 
    data_color(columns = c("hp"), 
               colors = col_numeric(palette = "Blues", 
                                    domain = c(0, 400))) %>% 
    tab_options(column_labels.hidden = TRUE) %>% 
    as_raw_html() # return as html
}

good_mpg_table <- 
  mtcars %>% 
  mutate(good_mpg = ifelse(mpg > 20, "Good mileage", "Bad mileage"), 
         car_name = row.names(.)) %>% 
  filter(good_mpg == "Good mileage") %>%
  head(5) %>% 
  arrange(hp) %>% 
  select(car_name, hp) %>% 
  hp_table()

bad_mpg_table <- 

  filter(good_mpg == "Bad mileage") %>% 
  head(5) %>% 
  arrange(hp) %>% 
  select(car_name, hp) %>% 
  hp_table() 

data_tables <- data.frame(good_table = good_mpg_table, 
                          bad_table = bad_mpg_table)

data_tables %>% 
  gt() %>% 
  fmt_markdown(columns = TRUE) %>% #render cell contents as html
  cols_label(good_table = "High mileage", 
             bad_table = "Low mileage")

@Daniel,感谢您分享这个!这个可以派上用场。

为了使代码更紧凑一些,您可以使用 group_map(或 do)在 dplyr 工作流程中生成两个表,然后像您一样加入它们:

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)