Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 984
sharoz Avatar asked Jan 10 '14 21:01

sharoz


People also ask

How do I show output in R markdown?

If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .

How do you produce bold text in R markdown?

Bold, indent, underline, strikethrough**bold** produces bold. ~~strikethrough~~ produces strikethrough.

How do you underline text in Rmarkdown?

If you really want to underline text you can use <span style="text-decoration:underline">underline this text</span> for HTML output or $\text{\underline{This sentence underlined using \LaTeX}}$ for pdf output.

How do I embed a plot in R markdown?

You can embed an R code chunk like this: ```{r} summary(cars) ``` You can also embed plots, for example: ```{r, echo=FALSE} plot(cars) ``` Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.


1 Answers

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.

like image 60
Ramnath Avatar answered Sep 30 '22 04:09

Ramnath