16

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!

user2048508
  • 335
  • 1
  • 9
  • Check out: http://stackoverflow.com/questions/37755037/how-to-add-code-folding-to-output-chunks-in-rmarkdown-html-documents/37839683#37839683 It allows to specifically fold single chunks (outputs, source or both) – Martin Schmelzer Aug 03 '16 at 16:45
  • If you're looking for a simple workaround, you can check out https://stackoverflow.com/a/53870441/3430463 – 7hibault Dec 21 '18 at 07:34
  • Possible duplicate of [Code folding for individual chunks in R Markdown?](https://stackoverflow.com/questions/42543431/code-folding-for-individual-chunks-in-r-markdown) – 7hibault Oct 10 '19 at 12:38

2 Answers2

1

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

stevec
  • 41,291
  • 27
  • 223
  • 311
0

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.

CubicInfinity
  • 163
  • 1
  • 10