【问题标题】:Interactively show/hide code R Markdown/Knitr report交互式显示/隐藏代码 R Markdown/Knitr 报告
【发布时间】:2016-01-14 07:47:00
【问题描述】:

有没有办法在 R Markdown/Knitr 报告中以交互方式显示/隐藏代码?

【问题讨论】:

  • 请给出一个最小的示例脚本,你如何处理它的命令,以及用户如何阅读和交互的更完整的描述。有很多做 Markdown/knitr 的方法,它有助于准确地了解。

标签: r knitr r-markdown


【解决方案1】:

如果我理解正确,您至少可以通过使用 HTML 输出来做到这一点,就像在这个最小的示例中一样:

---
title: "Toggle Code boxes"
output: html_document
date: "January 12, 2016"
---

First add the javascript to toggle boxes(remember to indent it)

  <script language="javascript"> 
    function toggle(num) {
      var ele = document.getElementById("toggleText" + num);
      var text = document.getElementById("displayText" + num);
      if(ele.style.display == "block") {
        ele.style.display = "none";
        text.innerHTML = "show";
      }
      else {
        ele.style.display = "block";
        text.innerHTML = "hide";
      }
   } 
  </script>

and then we have some R code with the toggle button wrapped around (also indented):

  <a id="displayText" href="javascript:toggle(1);">Show underlying code</a>
  <div id="toggleText1" style="display: none">

```{r}
x <- sample(100)
mean.x <- mean(x)
```

  </div>

The mean is `r mean.x`. Please click the link to see the source code.

  <a id="displayText" href="javascript:toggle(2);">Show underlying code</a>
  <div id="toggleText2" style="display: none">

```{r}
median.x <- median(x)
```

  </div>

And the median is `r median.x`. Please click the link to see the source code.

【讨论】:

  • 如果我总是想查看打印输出并显示/隐藏代码怎么办?
  • 我不确定这是否是最有效的解决方案,但作为解决方法,我建议您使用两个单独的块,在代码块中计算结果,然后将它们存储在那里。然后结果块只打印它们,你保留的后一个总是可见的,你只需切换第一个。
猜你喜欢
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 2017-01-21
  • 1970-01-01
  • 2021-06-13
相关资源
最近更新 更多