user2048508
user2048508

Reputation: 335

Default code folding by individual chunk in rmarkdown

I am writing up a lesson in HTML using rmarkdown to demonstrate how to implement analytic methods in R, and because of this the document has a lot of code that is needed to understand those methods, but also a lot of code that is used only for generating plots and figures. I would like to show the first sort of code by default, and leave the plotting code available for students to view but hidden by default.

I know that rmarkdown has recently added support for code folding by setting the code_folding html_document argument to either show or hide. However, this either leaves all code chunks unfolded or folded by default -- is there any way to indicate whether individual code chunks should be shown or folded by default while allowing code folding?

Thank you!

Upvotes: 16

Views: 2334

Answers (2)

CubicInfinity
CubicInfinity

Reputation: 312

David Fong provided a perfect solution for this in their answer: https://stackoverflow.com/a/56657730/9727624

To override the state, use {r class.source = "fold-hide"} if the yaml setting is show, and {r class.source = "fold-show"} if the setting is hide.

Upvotes: 1

stevec
stevec

Reputation: 52198

I arrived here wondering the same thing. This is a not a perfect solution, but I write the code twice: once in regular markdown (so it displays - note no {r} after the three backticks), and another time in a code chunk (so it runs).

Example:

This runs but doesn't display the actual code
```{r}
5 * 5 
```


This results in both the code and execution being displayed
```
5 * 5
```
```{r}
5 * 5 
```

Which results in:

enter image description here

Upvotes: 1

Related Questions