TarJae
TarJae

Reputation: 78927

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

Upvotes: 2

Views: 743

Answers (2)

David Gohel
David Gohel

Reputation: 10675

You can also use tabulator()+as_flextable() functions:

library(dplyr)
library(flextable)  
mtcars %>% 
  select(mpg, cyl, am) %>% 
  group_by(cyl, am) %>% 
  summarise(mean_mpg = mean(mpg),
            sd_mpg = sd(mpg)) %>% 
  tabulator(rows = "cyl", columns = "am",
            `μ` = as_paragraph(mean_mpg), 
            `σ` = as_paragraph(sd_mpg)) |> 
  as_flextable()

enter image description here

Upvotes: 2

M Aurélio
M Aurélio

Reputation: 912

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

Upvotes: 1

Related Questions