Support

Including verbatim R code chunks inside R Markdown

Follow

Sometimes you may want to include verbatim R code chunks inside R Markdown documents. For example, you might want to write instructions that demonstrate R code chunk options. In that case you will want to display the entire syntax for an R code chunk inside your R Markdown document. However, including verbatim R code chunks with R Markdown requires an unconventional solution (i.e. hack).

Problem

When you knit an R Markdown document, the R code chunks are evaluated using R. The R code chunks have the form ```{r}...``` where the contents in ... are passed to R. If you want to include the R code chunk verbatim (i.e. without executing in R), you need a way to avoid processing the content in R. Unfortunately, simply nesting an R code chunk inside more backticks doesn't work.

Solution

One solution for including verbatim R code chunks (see below for more) is to insert hidden inline R code immediately before your R code chunk. If you wrap this code within a markdown code block, the rendered output will display the verbatim R code chunk — including backticks.

  1. Start verbatim output: ````markdown
  2. Insert hidden inline R code: `r ''`
  3. Start and end the R code chunk you want to display: ```{}...```
  4. End verbatim output: ````

Example

Write this code in your R Markdown document:

````markdown
`r ''````{r}
plot(cars)
```
````

Knit the document and the code will render like this in your output:

```{r}
plot(cars)
```

References

For more examples and explanations, please see:

Comments