5.6 Verbatim code chunks

Typically we write code chunks and inline expressions that we want to be parsed and evaluated by knitr. However, if you are trying to write a tutorial on using knitr, you may need to generate a verbatim code chunk or inline expression that is not parsed by knitr, and we want to display the content of the chunk header.

Unfortunately, we cannot wrap the code chunk in another layer of backticks, but instead we must make the code chunk invalid within the source code by inserting `r ''` in the chunk header. This will be evaluated as an inline expression to an empty string by knitr. For this example, the following “code chunk” in the source document:

  1. ```{r, eval=TRUE}`r ''`
  2. 1 + 1
  3. ```

will be rendered as:

  1. ```{r, eval=TRUE}
  2. 1 + 1
  3. ```

in the output. The inline expression is gone because it is substituted by an empty string. However, that is only the first step. To show something verbatim in the output, the syntax in Markdown is to wrap it in a code block (indent by four spaces or use backtick fences). This will be the actual source if you want to see the output above:

  1. ````
  2. ```{r, eval=TRUE}`r ''`
  3. 1 + 1
  4. ```
  5. ````

Why four backticks? That is because you have to use at least N+1 backticks to wrap up N backticks.

5.6.1 Show a verbatim inline expression

There are multiple ways to show a verbatim inline expression. The first way is to break the inline expression after `r, e.g.,

  1. This will show a verbatim inline R expression `` `r
  2. 1+1` `` in the output.

In the output document, you should see:

This will show a verbatim inline R expression `r 1+1` in the output.

The trick works for two reasons: (1) a single line break is often the same as a space to Markdown parsers (by comparison, two consecutive line breaks means starting a new paragraph); (2) knitr requires a space after `r to parse it; if the space is missing, it will not be treated as an inline expression.

Another way to show a verbatim inline R expression is to wrap the R code in knitr::inline_expr(), e.g.,

  1. This will show a verbatim inline R expression
  2. `` `r knitr::inline_expr("1+1")` `` in the output.

I’d recommend the second way, because the first way is more or less a hack taking advantage of the Markdown syntax and knitr’s parser.