LaVOZs

The World’s Largest Online Community for Developers

'; R Markdown: Prevent page break within code results - LavOzs.Com

I have a Rmarkdown document which I want to knit into a PDF document. How can I prevent page breaks within code chunk results.

The results are not longer than one page. It would just be sensible if a too-long-for-the-rest-of-the-page result would be moved to the next page instead of displaying a table header on page 1 and the rest of the table on page 2.

Sorry, if the answer to this is out there somewhere. I didn't find it.

Edit: Some code was requested. So, here we go.

---
title: "How to prevent page breaks in R Markdown code results"
author: "Georgery"
date: "10 January 2017"
output: pdf_document
---

# Create
# some
# headlines
# to
# fill
# the
# page
# a
# little
# and
# even
# a 
# little
# more
...and now create some code results
```{r, echo = FALSE}
data.frame(
    a = 1:20
    ,b = letters[1:20]
)
```

I'm not sure this can be done automatically, but perhaps including \newpage or \pagebreak as appropriate would force the output to a new page.

Coming back to this after quite some time with a solution.

What works out for me is simply using kable() from the knitr package. This way the table gets rendered as one object. Here's the code:

---
title: "How to prevent page breaks in R Markdown code results"
author: "Georgery"
date: "10 January 2017"
output: pdf_document
---

# Create
# some
# headlines
# to
# fill
# the
# page
# a
# little
# and
# even
# a 
# little
# more
...and now create some code results

```{r, echo = FALSE, warning = FALSE, message = FALSE}
library(knitr) # needed to make the table a separate object on only one page
library(kableExtra) # not needed but makes the table nicer
library(tidyverse) # not needed at all, but I like the pipe (%>%)

data.frame(
    a = 1:20
    , b = letters[1:20]) %>%
    kable("latex", booktabs = TRUE) %>% # This already puts it on a separate page
    kable_styling(latex_options = c("striped"))
```
Related
Inserting a page break within a code chunk in rmarkdown (converting to pdf)
Rstudio Rmarkdown ouput is different than html and pdf
RMarkdown: Option to control number of results per page in SQL results?
texreg in Rmarkdown/knitr
RMarkdown pdf document chunk output exceeds page margins
Indent R Markdown code block in PDF/LaTeX output
R Markdown refuses to suppress code chunk output
Read in characters from txt and knit with page break
Line breaks in directory using knitr/R Markdown