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?

2

There are 2 best solutions below

1
On

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

2
On

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