rlatexr-markdownpage-break

Insert Pagebreak for Output after Code Chunk


I have a .Rmd file which I am converting to PDF. For layout reasons, I want to display the generated output plot of my code chunk on the next page even though it would just fit in underneath.

Normally with text etc. one would use

\pagebreak

But how can I signalize the code chunk that it should display its output on the next page? Thanks for helping!


Solution

  • You can write a knitr hook to set up a chunk option to do this.

    So here I have modified the source chunk hook and created a chunk option next_page which, if TRUE, the output of that chunk will be on the next page.

    ---
    title: "Chunk Output in Next page"
    output: pdf_document
    date: "2022-11-25"
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    ## R Markdown
    
    ```{r, include=FALSE}
    library(knitr)
    
    default_source_hook <- knit_hooks$get('source')
    
    knit_hooks$set(
      source = function(x, options) {
        if(isTRUE(options$next_page)) {
          paste0(default_source_hook(x, options),
            "\n\n\\newpage\n\n")
        } else {
          default_source_hook(x, options)
        }
      }
    )
    ```
    
    ```{r, next_page=TRUE}
    plot(mpg ~ disp, data = mtcars)
    ```
    

    chunk output in the next page