Home > database >  pivot wider - create two levels of headers for better readability
pivot wider - create two levels of headers for better readability

Time:10-31

There are six regression models. I used pivot wider but it is difficult to read. Can I use two level of headers -

  • first level - regression model
  • second level - estimate, tstat
library(dplyr)

regression <- c(rep("A", 3), rep("B", 3), rep("C", 3), rep("D", 3), rep("E", 3), rep("F", 3))
attribute <- rep(c("b0", "b1", "b2"), 6)
estimate <- round(runif(n = 18, min = 0, max = 10), 2)
tstat <- round(runif(n = 18, min = 0, max = 10), 2)

# tibble
tbl <- tibble(regression, attribute, estimate, tstat)

# pivot wider
tbl <- tbl %>% 
  pivot_wider(names_from = regression,
              values_from = c("estimate", "tstat"))

CodePudding user response:

One option is separate_header from ftExtra

library(ftExtra)
library(dplyr)
library(tidyr)
library(stringr)
tbl %>% 
     pivot_wider(names_from = regression,
                 values_from = c("estimate", "tstat")) %>% 
     rename_with(~ str_replace(., "(.*)_(.*)", "\\2_\\1"), -1) %>%
     as_flextable() %>%
     separate_header()

-output

enter image description here


Or may use span_header

library(flextable)
tbl %>%  
  pivot_wider(names_from = regression,
              values_from = c("estimate", "tstat")) %>%   
  rename_with(~ str_replace(., "(.*)_(.*)", "\\2_\\1"), -1) %>% 
  select(attribute, order(str_remove(names(.)[-1], "_.*"))   1) %>% 
  as_flextable() %>% 
  span_header()  %>% 
  align(align = "center", part = "all")

-output enter image description here


If we need to make some column bold,

tbl %>%  
    pivot_wider(names_from = regression,
                values_from = c("estimate", "tstat")) %>%   
    rename_with(~ str_replace(., "(.*)_(.*)", "\\2_\\1"), -1) %>% 
    mutate(across(ends_with('tstat'),  ~sprintf('**%.2f**', .))) %>% 
    select(attribute, order(str_remove(names(.)[-1], "_.*"))   1) %>% 
    as_flextable() %>% 
    span_header()  %>% 
    align(align = "center", part = "all") %>% 
    colformat_md()

-output

enter image description here

  • Related