rkableextra

Repeating grouped headers across pages in kableExtra


I'm putting together an R markdown document to render a pdf, which includes a long table that spans multiple pages. In that table, some of the columns are grouped, and I'm adding headers above to group the 2nd and 3rd column and the 4th and 5th column. The problem that I'm running into is that the headers from add_header_above are not being repeated on the second page. I've included a reproducible example below.

Currently, only the lower level headers ("Category", "n", "%", "n", "%") are being repeated on the second page. Ideally, I'd like for the "Group 1" and "Group 2" headers to be repeated as well.

Does anyone know how that can be done?

Thanks!

Also, please forgive the 3 backticks to close the code chunks not being consecutive. I couldn't figure out how to escape them so that the full example from the Rmd would be displayed together.

---
title: "Test"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(tidyverse)
library(knitr)
library(kableExtra)
```

Some text to anchor the first table.

```{r test-table}
tibble(col1 = rep("Random text", 80),
       n1 = 1:80,
       perc1 = 1:80,
       n2 = 1:80,
       perc2 = 1:80) %>% 
  kbl(col.names = c("Category", "n", "\\%", "n", "\\%"),
      caption = "Reproducible caption",
      longtable = TRUE, escape = FALSE, booktabs = TRUE, linesep = "") %>% 
  kable_styling(latex_options = c("HOLD_position", "repeat_header"),
                position = "left") %>% 
  add_header_above(c(" " = 1,
                     "Group 1" = 2,
                     "Group 2" = 2)) 
```

Solution

  • The developers of kableExtra were able to resolve this issue. Details found here. add_header_above must be placed prior to kable_styling

    ---
    title: "Test"
    output: pdf_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    library(tidyverse)
    library(knitr)
    library(kableExtra)
    ```
    
    Some text to anchor the first table.
    
    ```{r test-table}
    tibble(col1 = rep("Random text", 80),
           n1 = 1:80,
           perc1 = 1:80,
           n2 = 1:80,
           perc2 = 1:80) %>% 
      kbl(col.names = c("Category", "n", "\\%", "n", "\\%"),
          caption = "Reproducible caption",
          longtable = TRUE, escape = FALSE, booktabs = TRUE, linesep = "") %>% 
      add_header_above(c(" " = 1,
                         "Group 1" = 2,
                         "Group 2" = 2)) %>%
      kable_styling(latex_options = c("HOLD_position", "repeat_header"),
                    position = "left")
    ```