Search code examples
rr-markdownkablekableextraflextable

r-markdown - dynamic mutli-line header with second line the same


I am trying to create a multi-line header in r-markdown but I am having trouble 1.) making it dynamic and 2.) allowing the second line of the header be the same.

For example, in the below data set, you can see there are two groups, Petal and Septal. Each have length and width.

library(tidyverse)

data <- iris[c(1, 51, 101), ] %>% 
  gather(key = key, value = value, -Species) %>% 
  separate(col = key, into = c("Group", "key"), sep = "\\.") %>% 
  spread(key = key, value = value, )

data

#       Species      Group   Length Width
# 1     setosa       Petal   1.4    0.2
# 2     setosa       Sepal   5.1    3.5
# 3 versicolor       Petal   4.7    1.4
# 4 versicolor       Sepal   7.0    3.2
# 5  virginica       Petal   6.0    2.5
# 6  virginica       Sepal   6.3    3.3

I would like the outcome to be a multi-line header with groups by flower part (grouped by unique values, what ever they may be) and length and width as the second line. Like the below:

# --------------------------------------------
#            Petal            Sepal
# --------------------------------------------
# Species    Length  Width    Length    Width
# --------------------------------------------
# setosa     1.4     0.2      5.1       3.5
# versicolor 4.7     1.4      7         3.2
# virginica  6       2.5      6.3       3.3
# --------------------------------------------

I've been experimenting with kable and flextable packages, but the examples seem to hard-code the headers which I am trying to avoid.


Solution

  • With flextable, it should be something like that:

    library(tidyverse)
    library(flextable)
    
    data <- iris[c(1, 51, 101), ]
    
    header_df <- tibble( key = colnames(data) ) %>% 
      separate(col = key, into = c("Group1", "Group2"), sep = "\\.", remove = FALSE, fill = "left")
    
    data %>% 
      select(Species, everything()) %>% 
      flextable() %>% 
      set_header_df(mapping = header_df, key = "key") %>% 
      merge_h(part = "header") %>% 
      theme_booktabs()
    

    enter image description here