Print a code chunk as is

Sometimes we do not want to evaluate a chunk, and we just want to include a chunk literally, e.g. when writing tutorials. Two examples have been given:

The R code chunks in these examples are still identified by knitr. If we do not want to evaluate the code at all, there is another approach, which is to break the chunk syntax by adding an empty string as inline R code.

For Markdown, we can add an empty string after ```r; knitr will ignore this code chunk but also replace inline R code with the empty string. Here is one example (it is indented by 4 spaces because we want to show it in a preformatted block in the HTML output):

```r`r ''`
n = 10
rnorm(x)
```

By comparison, this chunk will be identified by knitr as usual:

n = 10
rnorm(n)

Another way (discovered by Hadley Wickham) is to add a zero-width space in the chunk header, e.g.

`​``{r eval=TRUE}
n = 10
rnorm(n)
```

Note the zero-width space is normally invisible in the web browser, and may also be invisible in your text editor. Trust me, there is a zero-width space after the first backtick in the above code chunk even if you cannot see it (the Emperor does have clothes). The RStudio IDE can show it as a red dot.



Try the parsermd package in your browser

Any scripts or data that you put into this service are public.

parsermd documentation built on May 20, 2021, 5:08 p.m.