haozhu233 / kableExtra

Construct Complex Table with knitr::kable() + pipe.
https://haozhu233.github.io/kableExtra/
Other
691 stars 147 forks source link

Repeating grouped headers across pages in kableExtra #868

Open JeffreyCHoover opened 6 days ago

JeffreyCHoover commented 6 days ago

Hello!

Cross-referencing a post I added to StackOverflow here, since no one was able to point me to a solution on SO.

I was 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. I think this would be a valuable addition to conform with many formatting standards for tables (e.g., APA 7 formatting) as well as generally increasing the readability of tables spanning multiple pages.

Thanks!

---
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.

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)) 
rhurlin commented 6 days ago

Hi @JeffreyCHoover, By simply moving add_header_above() above kable_styling() it works for me:

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") 

Would you please give a quick feedback if it works for you? Thanks.

HTH, Rainer

JeffreyCHoover commented 6 days ago

That worked perfectly! Thank you so much!

I'll close this out since the issue has been resolved.

dmurdoch commented 6 days ago

I'm re-opening it, because the issue isn't really resolved -- we just have a workaround.