You can collapse elements using Javascript. The jQuery JavaScript framework makes this easy enough with the hide and show methods.
In the folder containing your Rmd template, create a subfolder named script and save the jQuery file . (You don't have to be there, but it's a reasonably standard location.)
Add this code to the top of your Rmd file.
<script type="text/javascript" language="javascript" src="script/jquery-1.10.2.min.js"> </script>
For Markdown, the closing tag must be on a separate line .
Alternatively, if your report will mainly be read on machines with Internet access, you you can should use the jQuery version hosted by Google.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" > </script>
Then add another script block for your collapsing logic. The exact implementation is up to you; there are lots of examples on the internet.
The key to simplifying the folding / extension logic is that the elements you control have a consistent class (or template for their identifiers).
source share