How to convert Rmd code chunks to simple html snippets

Is it possible to convert code chunks in an Rmd document to html without creating a whole web page?
I would like to use rmarkdown to format some content containing R code - but I would like the resulting html to be embedded in an existing html document.

For example, the following code:

### Example
```{r}
a <- 1 + 1
a
```

should result in the html snippet:

<h3>Example</h3>
<pre><code class="lang-r">
a &lt;- 1 + 1
a
</code></pre>

At the moment, I can only do this using rmarkdown::render() which generates a complex self-contained file with embedded script elements that conflict with the existing website.

I am sure such a solution must exist, but I have not had any luck finding it!

1 Like

I think the output format html_fragment() will do what you need.

For example, if you have a file named fragment.Rmd that contains the following:

### Example
```{r}
a <- 1 + 1
a
```

You can render it to an HTML fragment with:

library(rmarkdown)
render("fragment.Rmd", html_fragment())

And the result is fragment.html which contains the following:

<div id="example" class="section level3">
<h3>Example</h3>
<pre class="r"><code>a &lt;- 1 + 1
a</code></pre>
<pre><code>## [1] 2</code></pre>
</div>

Update: I realized that in your example you didn't evaluate the code chunk. To do this, you can specify the chunk option eval=FALSE. Then the output is closer to what you wanted:

<div id="example" class="section level3">
<h3>Example</h3>
<pre class="r"><code>a &lt;- 1 + 1
a</code></pre>
</div>
3 Likes

Many thanks!

html_fragment() is exactly what I was looking for. I managed to miss this even while hunting through the documentation.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.