Collapse / hide shapes in R markdown
In my rmarkdown document, I can show and hide the code with the following - which creates a handy button to the right of the document, before each block of code:
output:
html_document:
code_folding: hide
Is there a similarly convenient way to hide tables or numbers? If so, please provide a link as I could not find it. Otherwise a workaround would be appreciated, thanks!
source to share
If you add this to the end of your .Rmd
file
<script>
$( "input.hideshow" ).each( function ( index, button ) {
button.value = 'Hide Output';
$( button ).click( function () {
var target = this.nextSibling ? this : this.parentNode;
target = target.nextSibling.nextSibling.nextSibling.nextSibling;
if ( target.style.display == 'block' || target.style.display == '' ) {
target.style.display = 'none';
this.value = 'Show Output';
} else {
target.style.display = 'block';
this.value = 'Hide Output';
}
} );
} );
</script>
and then before each chunk you want to switch:
<input type=button class=hideshow></input>
(adapted from here: https://groups.google.com/forum/#!topic/knitr/d37E0mP3w6k )
Note: this will work if you show the code - if you hide the code (with echo = FALSE
) change
target = target.nextSibling.nextSibling.nextSibling.nextSibling;
to
target = target.nextSibling.nextSibling;
Note 2: if you want to use a parameter code_folding
, change
target = target.nextSibling.nextSibling.nextSibling.nextSibling;
to
target = target.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;
source to share
I was unable to get the above solution (or others I found) to work consistently, but using inline html (Bootstrap example / solution) I found at W3schools.com works well in Rmarkdown.
I am using it to show a simple graph in the html output in the example below. It should work with any chunk output:
<button class="btn btn-primary" data-toggle="collapse" data-target="#BlockName"> Show/Hide </button>
<div id="BlockName" class="collapse">
```{r}
plot(mtcars$disp, mtcars$mpg)
```
</div>
source to share