Can markdown expressions and results be interleaved in the same block?

knitr, r, r-markdown

Solution

This can be done using `hooks`. Add the following code chunk right at the top of your `Rmd` document. It uses the document hook which is run on the `md` file at the last stage of `knitting`. The hook defined below identifies subsequent code chunks without any text chunk in between and collapses it into one.

{r setup, cache = F, echo = F} knitr::knit_hooks$set(document = function(x){ gsub("

\n*

r*\n*", "", x) })

`

NOTE. It is important to set `cache = F` in this chunk so that this code is always run.

Problem

A simple chunk in R markdown: ```` ```{r} 1 + 2 3 + 4 ``` ```` Would produce the following when knitr converts to html: ``` <pre><code class="r">1 + 2</code></pre> <pre><code>## 3</code></pre> <pre><code class="r">3 + 4</code></pre> <pre><code>## 7</code></pre> ``` I'm trying to output the expressions and results in one block ``` <pre><code class="r"> 1 + 2 ## 3 3 + 4 ## 7 </code></pre> ``` I've tried tinkering around with the chunk parameters (e.g. results and echo) to no avail. Is there any way to accomplish this? Note: I could probably hack at CSS with `::first` and `::last` selectors, but I'm curious as to whether there's a built-in option.

Original source