Inserting a page break within a code chunk in rmarkdown (converting to pdf)
Asked Answered
T

3

26

I am using rmarkdown, pandoc and knitr to create a pdf including chunks of r code. Within a code chunk I have a for loop which prints a number of graphs and some statistical output.

I would like to insert a page break into the loop (to appear in the pdf output). This page break would occur after each graph is printed, to ensure each graph is printed on one page and the statistical output on the next.

I have been unable to find a way of including a page break in my r code chunk. I have tried cat("\\newpage") and cat("\\pagebreak") in the hopes it would be recognized by pandoc but to no avail (it is just printed verbatim in the final pdf).

Suggestions appreciated. Here is the code I have so far:

```{r, echo =FALSE, message=FALSE, warning=FALSE, comment=NA, results='asis'}
library("markdown") 
library("rmarkdown") 
library("knitr")
library("ggplot2")
for (v in Values){

# read in file
testR <- read.csv(file.path, header=T)

print(ggplot(testR, aes(x=Time, y=Value, color=Batch)) + geom_point(size = 3) +
xlab ("Timepoint") +
ylab (v) +
scale_x_continuous(breaks=seq(0, 60, by=6)) +
ggtitle(paste("Scatterplot of Batches for ", v, sep="")))
ggsave(paste(timestamp, "__", 
       "Scatterplot of Batches for ", v, ".jpeg", sep = "")) 

cat("\\pagebreak")
writeLines(v)
writeLines("\n")
writeLines("\n Test for homogenity of slopes \n")
av1 <- aov(Value~Time*Batch, data=testR)
print(summary(av1))
}
```
Tantrum answered 5/8, 2015 at 11:16 Comment(0)
C
42

See below a reduced and reproducible example. The answer and some general remarks:

  • To dynamically create new pages or sections in a markdown document use results='asis' in the chunk options.
  • You have to add a linebreak (\n) after \\pagebreak or else "ValueForV" will be pasted directly after "\linebreak", which results in an Undefined control sequence error.
  • Make sure that \newpage and \pagebreak are in a separate line by using linebreaks \n before.
  • Escape \newpage and \pagebreak (i.e., \\newpage, \\pagebreak).

    ---
    title: "test"
    output: pdf_document
    ---
    
    ```{r, echo=FALSE, results='asis'}
    for (i in 1:3) {
      print(ggplot2::qplot(i, i+1))
      cat("\n\n\\pagebreak\n")
      writeLines("ValueForV")
    }
    ```
    
Calamus answered 5/8, 2015 at 11:46 Comment(7)
I'm afraid that still just prints \newpage, with an extra 2 blank lines in front of itTantrum
This is strange.. could you please edit your questions and provide a minimal and reproducible example?Calamus
I had forgotten to add results='asis' when calling the function itself. However now no pdf is produced and this error given "! Undefined control sequence. l.105 \newpageDW"Tantrum
First of all, please see here on how to provide a reproducible example. It is really hard to find the errors if there is only part of your code. On topic: have you escaped \newpage (i.e., \\newpage)?Calamus
Okay so found the issue. As you can see in my code I was using writeLines(v) directly after cat which was creating \newpageValueForV. Inserting \n after \n\n\\newpage solves this. Do you want to adjust your answer to reflect such? And then I can mark as correctTantrum
Glad that you found it. I tried to adjust my answer accordingly and more or less summarised what to concider when dynamically creating rmarkdown documents.Calamus
This does not work if the output is beamer_presentation. Only for pdf_document.Thorough
M
3

How to insert a page break within an Rstudio .Rmd code chunk that survives conversion to PDF:

If the \newpage and \pagebreak latex macros aren't working for you, here's a workaround using HTML.

For example:

---
title: "The Rent"
output:
  pdf_document: default
  html_document: default
---

# This is pre-chunk text.

```{r, echo=FALSE, results='asis'}
print("Now we're <b>inside the chunk</b>, using the power of HTML.<br><br><br>!")

print("As you can see from the following diagram")
cat("\n")
print("The rent...<br>")
print(plot(1:10))

print("<P style='page-break-before: always'>")    #forced new-page happens here.

print("<h1>Is too damned high!!</h1>")
writeLines("\n")
print("Finished")
cat("\n\n")
```
This is post chunk text.

Produces this for me:

enter image description here

The key ingredients is the print("<P style='page-break-before: always'>") and the {r, echo=FALSE, results='asis'} in the chunk header.

Marroquin answered 16/4, 2017 at 21:1 Comment(2)
I get [1] ”” where the page break should be, but no page break.Signor
@Signor same for me, no page break compiling the MWE provided by posterThorough
T
0

For beamer presentations, insert {.allowframebreaks} after frame header.

In this way, the LaTeX frame environment is created with the allowframebreaks option (i.e., \being{frame}[allowframebreaks].

Then you can use \framebreak or \pagebreak or newpage to insert a frame break.

Make sure that the plots that are supposed to fit in one frame actually fit in one frame, otherwise beamer will put the plot in the next frame automatically. You can make a plot fit in a single frame with out.height and/or out.width options (see R Markdown cookbok).

---
title: "test"
output: beamer_presentation
---

# Test {.allowframebreaks}

```{r, echo=FALSE, results='asis', out.height="80%"}
for (i in 1:3) {
  print(ggplot2::qplot(i, i+1))
  cat("\n\n\\framebreak\n")
  writeLines("ValueForV")
}
Thorough answered 14/5, 2023 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.