Create Multilevel Header Table from data frame in R

I have a tidy data frame like below

df <- data.frame(CONDITION = c(rep("PRE", 6), rep("POST", 6)),
                 CLASS = c(rep(c(rep("B1",3), rep("B2",3)),2)),
                 REGION = c("A1", "A2", "A3", "A1", "A2", "A3", "A1", "A2", "A3", "A1", "A2", "A3"),
                 VALUE = c(1,2,3,4,5,6,7,NA,9,10,11,NA)
)
library(dplyr)
library(tidyr)

df %>% drop_na()
   CONDITION CLASS REGION VALUE
1        PRE    B1     A1     1
2        PRE    B1     A2     2
3        PRE    B1     A3     3
4        PRE    B2     A1     4
5        PRE    B2     A2     5
6        PRE    B2     A3     6
7       POST    B1     A1     7
8       POST    B1     A3     9
9       POST    B2     A1    10
10      POST    B2     A2    11

Is there a way, to make multilevel header like table below? In the dataframe I have, there are some NA.

enter image description here

I have try to separate it to two dataframe and join it using cbind, and use library gt to create multilevel header manually, but It didn’t work, since there are difference in row length (The DF, have some NA)

>Solution :

We could reshape to wide with pivot_wider and then use span_header from ftExtra

library(dplyr)
library(tidyr)
library(flextable)
library(ftExtra)
df %>% 
    unite(CONDITION, CONDITION, CLASS) %>%
     pivot_wider(names_from = CONDITION, values_from = VALUE) %>%
     as_flextable() %>%
     span_header()

-output

enter image description here

Leave a Reply