R Markdown now has the option to automatically show or hide code chunks in your .Rmd document. However, this seems to only work with R code chunks.
---
output:
html_document:
code_folding: hide
---
```{r}
print("This code chunk will be hidden")
```
```{r, engine='bash'}
echo "This code chunk will not be hidden"
```{r, engine='python'}
print "Will this code chunk be hidden?"
```
```{r}
system('uname -srv',intern=T)
sessionInfo()
```
The only solution I have been able to come up with is to hide the code behind a blank tab
---
output:
html_document:
code_folding: hide
---
```{r}
print("This code chunk will be hidden")
```
# Source code {.tabset .tabset-pills}
## Hide Code
## Show Code
```{r, engine='bash'}
echo "This code chunk will not be hidden"
```
```{r, engine='python'}
print "Will this code chunk be hidden?"
```
```{r}
system('uname -srv',intern=T)
sessionInfo()
```
Is there a better solution to this which will enable code folding for all code chunks?
Menu Commands and ShortcutsEdit -> Folding: Collapse — Alt+L. Expand — Shift+Alt+L. Collapse All — Alt+O.
Chunk options The initial line in a code chunk may include various options. For example, echo=FALSE indicates that the code will not be shown in the final document (though any results/output would still be displayed). You use results="hide" to hide the results/output (but here the code would still be displayed).
You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS). There are a large number of chunk options in knitr documented at https://yihui.name/knitr/options.
The reticulate package includes a Python engine for R Markdown that enables easy interoperability between Python and R chunks.
Maybe R version plays a role here? For me, without any modifications, your code works as expected:
## R version 3.3.3 (2017-03-06)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: macOS Sierra 10.12.6
as for R studio
Version 1.0.136 – © 2009-2016 RStudio, Inc.
Of course, I have changed (from your initial post)
```{r, engine='bash'}
echo "This code chunk will not be hidden"
with
```{r, engine='bash'}
echo "This code chunk will not be hidden"
```
You can fix it in post-production too. I convert Rmd->HTML using rmarkdown::render() (R 3.4.1) and pandoc-1.17.2. The resulting HTML file uses different CSS classes for different languages, but only the <pre> class "sourceCode r" supports folding.
So, just change all non-"r" classes to "r" in the <pre> tags:
perl -i -pe 's/<pre class="sourceCode [^r]+">/<pre class="sourceCode r">/' myfile.html
The appearance of the code in the blocks will not change.
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