R Markdown: hide code blocks

12 Nov 2024language

In writing an R Markdown document to describe a within-host malaria model that I'm working on, I have focused on the HTML version of the document and made use of code folding to hide several code blocks by default.

The PDF version of the document includes the complete listing of each code block, but I instead wanted to remove the folded code blocks from the PDF version. And while it took me a long time to find a solution, the solution itself is quite simple.

For each folded code block:

```{r block_name, class.source = 'fold-hide'}
# Code goes here ...
```

use the echo option and is_latex_output() to hide the code block when exporting to PDF:

```{r block_name, class.source = 'fold-hide', echo = ! knitr::is_latex_output()}
# Code goes here ...
```

It's also possible to remove (sub)sections and code blocks entirely, unless exporting to a specific output format. For example, here is how to include headings and code blocks only for HTML output:

`r if (knitr::is_html_output()) '# My heading title'`

```{r block_name, include = knitr::is_html_output()}
# Code goes here ...
```