Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading