Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RMarkdown collapsible panel

Tags:

r

r-markdown

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:

enter image description here

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?

like image 277
rmf Avatar asked Sep 30 '18 09:09

rmf


People also ask

Does markdown support collapsible sections?

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.

What is Rmarkdown in Rstudio?

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.


1 Answers

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 collapsed

Expanded expanded

like image 55
OmaymaS Avatar answered Oct 04 '22 20:10

OmaymaS