Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

knitr - Code folding for individual chunks in R Markdown?

Is there a way to have code folding available for individual chunks in an R Markdown document, but not others (without writing customized JavaScript)?

I know I can use the code_folding YAML option, but that applies to the whole document. I'd like to enable it for individual chunks, but not all chunks.

[The reason is for writing a lab that contains instructions that should not be hideable, but with questions that have show/hide solutions.]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After rmarkdown 1.15

This has been implemented (see related issue, PR and NEWS.md). However you should note that this folds only the code and not the output. You need to add some extra config to hide the code by default and not evaluate it.

---
title: "Bohemian Rhapcodey"
output: 
  html_document:
    code_folding: hide
---

## Question 1

Are you in love with your car?

```{r class.source = NULL, eval = FALSE}
summary(cars)
```

## Question 2

Are you under pressure?

```{r class.source = NULL, eval = FALSE}
plot(pressure)
```

Try the knitted HTML on JSFiddle

Before rmarkdown 1.15

The issue was closed on july 2019 on GitHub. A workaround using the details element in html was suggested.

This can work for some use cases until it is actually implemented.

---
title: "Bohemian Rhapcodey"
output: html_document
---

## Question 1

Are you in love with your car?

<details>
  <summary>Toggle answer</summary>
  ```{r cars}
  summary(cars)
  ```
</details>

## Question 2

Are you under pressure?

<details>
  <summary>Toggle answer</summary>
  ```{r pressure}
  plot(pressure)
  ```
</details>

Try the knitted HTML on JSFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...