0

I'm creating a template file for R markdown / R notebook. There are several code chunks that I wish will remain folded when the .rmd is being opened. Is this possible?

Example

Let's say that we have the following code, and we save it (without the ##) into a file named my_file.rmd

## ---
## title: "R Notebook"
## output: html_notebook
## ---

## # step 0 -- my predefind functions
## ```{r my_func()}
## my_func <- function(x) {
##   x + 1
## }
## ```

## ```{r my_func_2()}
## my_func_2 <- function(x) {
##   x / 6
## }
## ```

## # step 1 -- your code here
## ```{r}

## ```

Is there a way we can open my_file.rmd — using RStudio — with the chunks {r my_func()} and {r my_func_2()} being folded upon opening the file?

Emman
  • 3,695
  • 2
  • 20
  • 44

2 Answers2

0

You coud use code_folding: hide YAML combined with class.source = 'fold-show' for he chuncks you want to show, see:

---
title: "R Notebook"
output:
  html_document:
    code_folding: hide
---

# step 0 -- my predefined functions
```{r my_func()}
my_func <- function(x) {
  x + 1
}
```

```{r my_func_2()}
my_func_2 <- function(x) {
  x / 6
}
```

# step 2 -- your code here
```{r class.source = 'fold-show'}
my_func_3 <- function(x) {
  x / 6
}
```

enter image description here

Waldi
  • 39,242
  • 6
  • 30
  • 78
  • thanks! But my question is aimed at the `.rmd` file (the source code), not the `html` output. – Emman Jun 08 '21 at 09:19
0

As long as you have a proper R chunks, you can fold the code inside the Rmd in Rstudio. I highly suggest you read up on knitr spin() too enter image description here

enter image description here

Daniel_j_iii
  • 3,041
  • 2
  • 11
  • 27
  • Thanks. The problem is not how to fold, but how to have the folded chunk remain folded when *re-*opening the `.rmd` file next time. – Emman Jun 12 '21 at 14:12
  • The next best thing is just a keyboard shortcut for folding the Chunk while in the IDE for hopefully a faster workflow. `Fold Selected windows(Alt+L) MacOS(Cmd+Option+L)` – Daniel_j_iii Jun 12 '21 at 14:43