rkableextrapagedown

How to use pagedown and kable in R to print a table followed by a page break


Been scratching my head over this one for a few days.

I am using the pagedown package to write a report with variable length tables. I am most familiar with and content to work with kableExtra tables. However, because there is variable length, and the longtable options are (far as I can tell) latex oriented and not an html paged option, I am trying to group and print chunks of tables. A simplified example would be every 10 rows writes a table and inserts the equivalent of a page break.

Here is a minimal example. The content may bleed off the margins in this example, and that's fine, I'm just concerned with the vertical spacing.

---
output: 
  pagedown::html_paged:
    toc: false
---

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

library(ggplot2)
library(kableExtra)
library(dplyr)
```

```{r, results='asis'}
tabs <- 
  ggplot2::mpg %>%
    dplyr::group_by(grp = ceiling(row_number()/20)) %>%
    summarise(tables = list(
      kable(cur_data()) %>%
        kable_styling() %>%
        collapse_rows(1, valign = 'top'))) %>%
      select(tables) %>%
      unlist()
  
for (i in 1:length(tabs)) {
  cat(tabs[i])
  cat('\newpage  ')
}
```

Solution

  • Usually you define page-breaks for your elements in a custom stylesheet. Tables produced with knitr::kable are classic table HTML elements. If we want to have a pagebreak after each table, we would define it in a stylesheet (e.g. custom.css) like

    table {
      font-size: 0.5em;  /* table width would extent the page margins otherwise */
      break-after: page; /* move the content following a table to the next page */
    }
    

    In our rmarkdown document we would only have to include the additional CSS styles:

    ---
    output: 
      pagedown::html_paged:
        toc: false
        css: [default, default-page, default-fonts, custom.css]
    ---
    

    Notice, that we include the three default stylesheets first and then add ours.

    The complete document would look like this:

    ---
    output: 
      pagedown::html_paged:
        toc: false
        css: [default, default-page, default-fonts, test.css]
    ---
      
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    
    library(ggplot2)
    library(kableExtra)
    library(dplyr)
    library(knitr)
    ```
    
    ```{r, results = 'asis', message=F, warning=F}
    tabs <- 
      ggplot2::mpg %>%
      dplyr::group_by(grp = ceiling(row_number()/20)) %>%
      summarise(tables = list(
        kable(cur_data()) %>%
          kable_styling() %>%
          collapse_rows(1, valign = 'top'))) %>%
      select(tables) 
    
    invisible(lapply(tabs$tables, cat))
    ```
    

    where I used invisible to hide unwanted output from lapply which evaluates each list item using cat.

    The result looks like this:

    enter image description here