As I am preparing tutorials for students, I need a way to hide content in collapsible panels which can be revealed by clicking on a button. I have got this to work using the code below. The RMarkdown file looks like this:
---
title: Collapsible Panel
output:
html_document:
theme: flatly
highlight: tango
---
<p>
<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample1" role="button" aria-expanded="false" aria-controls="collapseExample1">
Click For Answer
</a>
</p>
<div class="collapse" id="collapseExample1">
<div class="card card-body">
```{r}
hist(1:10)
```
</div>
</div>
And it looks like this when rendered:
This works! I can also control if the code and/or results must be shown by controlling the chunk options.
But, this is not optimal because the code is messy and ugly with all the raw html. Copy-pasting this multiple times is not ideal. The ID used collapseExample1
needs to be unique every time this code block is used.
Is there some way to package this block into a reusable unit like a function or something? I am thinking something like an R function, where I can pass in code to be evaluated (or code that don't need to be evaluated), chunk options (eval
, echo
, results
, etc..) and state of the panel (open/closed).
collapsible_panel(code=NULL,echo=TRUE,results="show",state="closed")
I have many unclear questions at this point. Can I run R chunks inside R chunks? Maybe I need to use child Rmd files? Do I need to write some custom javascript?
Short Answer: No, Markdown does not offer a feature like that directly, but with some work you might be able to build something that works. For a feature like that to work you would need some CSS and/or JavaScript to control the animations, etc.
R Markdown files are the source code for rich, reproducible documents. You can transform an R Markdown file in two ways. knit - You can knit the file. The rmarkdown package will call the knitr package.
Another simple solution that would work (but without buttons and styling).
```{r, eval=FALSE}
hist(1:10)
```
<details>
<summary>Click for Answer</summary>
```{r, echo=FALSE, eval=TRUE}
hist(1:10)
```
</details>
And here are the two states:
Collapsed
Expanded
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With