4.4 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 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 can’t wrap the code chunk in another layer of backticks, but instead we must make the code chunk invalid within the source code by inserting “ to 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:

`r ''````{r, eval=TRUE}
1 + 1
```

will be rendered as:

```{r, eval=TRUE}
1 + 1
```

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:

````
```{r, eval=TRUE}`r ''`
1 + 1
```
````

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

4.4.1 Show a verbatim inline expression

There are multiple ways to show a verbatim inline expression. I mentioned this trick for R Markdown documents in the FAQ:

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

The trick works due to 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. In the output document, you should see:

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

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

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