rgtsummaryflextable

How to span header with column in flextable or gtsummary


How can I get this

library(dplyr)
library(flextable)  
  mtcars %>% 
    select(mpg, cyl, am) %>% 
    group_by(cyl, am) %>% 
    summarise(mean_mpg = mean(mpg),
              sd_mpg = sd(mpg)) %>% 
    flextable()

enter image description here

To this:

enter image description here


Solution

  • We need tidyr::pivot_wider() and ftExtra::span_header(). If you wish to make the empty spaces between column use "empty" col_keys in flextable.

    library(tidyr)
    library(dplyr)
    library(flextable)  
    
    mtcars %>% 
      select(mpg, cyl, am) %>% 
      group_by(cyl, am) %>% 
      summarise(mean_mpg = mean(mpg),
                sd_mpg = sd(mpg)) %>% 
      pivot_wider(names_from = am, values_from = c(mean_mpg, sd_mpg), names_glue = "am {am}.{.value}", names_vary = "slowest") %>% 
      flextable(col_keys = c(names(.)[1],"blank1",names(.)[2:3], "blank2", names(.)[4:5] )) |> 
      ftExtra::span_header(sep = "\\.") |> 
      empty_blanks()
    
    

    enter image description here