RMarkdown 可折叠面板 [英] RMarkdown collapsible panel

查看:100
本文介绍了RMarkdown 可折叠面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我为学生准备教程时,我需要一种方法来隐藏可折叠面板中的内容,点击按钮即可显示这些内容.我已经使用下面的代码让它工作了.RMarkdown 文件如下所示:

---标题:可折叠面板输出:html_document:主题:平淡亮点:探戈---<p><a class="btn btn-primary" data-toggle="collapse" href="#collapseExample1" role="button" aria-expanded="false" aria-controls="collapseExample1">点击回答</a></p><div class="collapse" id="collapseExample1"><div class="card card-body">```{r}历史(1:10)``

渲染时看起来是这样的:

这有效!我还可以通过控制块选项来控制是否必须显示代码和/或结果.

但是,这不是最佳的,因为所有原始 html 的代码都是混乱和丑陋的.多次复制粘贴并不理想.每次使用此代码块时,collapseExample1 使用的 ID 必须是唯一的.

有什么办法可以把这个块打包成一个可重用的单元,比如函数之类的?我正在考虑类似 R 函数的东西,我可以在其中传入要评估的代码(或不需要评估的代码)、块选项(evalechoresults 等)和面板状态(打开/关闭).

collapsible_panel(code=NULL,echo=TRUE,results="show",state="closed")

此时我有很多不清楚的问题.我可以在 R 块中运行 R 块吗?也许我需要使用子 Rmd 文件?我需要编写一些自定义 javascript 吗?

解决方案

另一种可行的简单解决方案(但没有按钮和样式).

```{r, eval=FALSE}历史(1:10)``<详情><summary>点击答案</summary>```{r, echo=FALSE, eval=TRUE}历史(1:10)``</详情>

这里有两个状态:

收起

扩展

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?

解决方案

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

这篇关于RMarkdown 可折叠面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆