Including verbatim R code chunks inside R Markdown


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).


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.


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: ````


Write this code in your R Markdown document:

`r ''````{r}

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



For more examples and explanations, please see: