Reputation: 6345
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.
Upvotes: 8
Views: 276
Reputation: 55695
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.
Upvotes: 7