Search code examples
rr-markdownknitrpre

R-markdown: Add an empty line between echoed code and result output


To combine the echoed R code and outputted result in knitr there is a handy collapse=TRUE option. However by default it leaves no space between them i.e. given the following Rmd:

```{r, echo=TRUE, include=TRUE, collapse=TRUE}
x <- matrix(1:6, nrow=2)
x
```

It would produce this output wrapped in a <pre> tag:

x <- matrix(1:6, nrow=2)
x
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6

What I would like instead is to get an empty line separating the output and code, but still being combined into a single <pre> element.

x <- matrix(1:6, nrow=2)
x

##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6

Is there a way to achieve this? I tried adding an empty line to the end of the R chunk, but seems like it was removed.


Solution

  • You can define a new chunk option instead of collapse using knitr chunk hooks that collapses code and output with additional whitespace. For instance, you could include in the setup chunk:

    Rmarkdown

    ---
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    hook_chunk = knitr::knit_hooks$get('chunk')
    
    knitr::knit_hooks$set(chunk = function(x, options) {
      regular_output = hook_chunk(x, options)
      # collapse with vspace if collapse_vspace is TRUE
      if (isTRUE(options$collapse_vspace))
        gsub("```\n\n```", "", regular_output)
      else
        regular_output
    })
    
    knitr::opts_chunk$set(collapse_vspace = TRUE)
    ```
    
    ```{r, echo = TRUE}
    x <- matrix(1:6, nrow=2)
    x
    ```
    

    HTML output

    htmloutput

    Some useful references: