Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interactively show/hide code R Markdown/Knitr report

Is there a way to show/hide code interactively in a R Markdown/Knitr report?

like image 659
Guillaume Avatar asked Jan 14 '16 07:01

Guillaume


People also ask

How do you show code but hide output in R Markdown?

You use results="hide" to hide the results/output (but here the code would still be displayed). You use include=FALSE to have the chunk evaluated, but neither the code nor its output displayed.

How do I hide code markdown?

Hide source code: ```{r, echo=FALSE} 1 + 1 ``` Hide text output (you can also use `results = FALSE`): ```{r, results='hide'} print("You will not see the text output.") ``` Hide messages: ```{r, message=FALSE} message("You will not see the message.") ``` Hide warning messages: ```{r, warning=FALSE} # this will generate ...

How do I show code chunks in R Markdown?

Code chunks in an R Markdown document contain your R code. All code chunks start and end with ``` – three backticks or graves.

How do I show output in R Markdown?

If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .


1 Answers

If I understood you correctly, you could do that at least by using the HTML output, like in this minimal example:

---
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.
like image 160
Daniel Fischer Avatar answered Sep 28 '22 00:09

Daniel Fischer