R Markdown中单个块的代码折叠?

bea*_*ber 25 r knitr r-markdown

有没有办法在R Markdown文档中为单个块提供代码折叠,而不是其他(不编写自定义JavaScript)?

我知道我可以使用code_foldingYAML选项,但这适用于整个文档.我想为单个块启用它,但不是所有块.

[原因是编写一个实验室,其中包含不应隐藏的说明,但有问题显示/隐藏解决方案.]

7hi*_*ult 6

在rmarkdown 1.15之后

这已经实现(请参阅相关问题PRNEWS.md)。但是,您应该注意,这仅折叠代码,而不折叠输出。您需要添加一些额外的配置来默认隐藏代码而不对其进行评估。

---
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)
```
Run Code Online (Sandbox Code Playgroud)

在JSFiddle上尝试编织的HTML

在rmarkdown 1.15之前

该问题已于2019年7月在GitHub上关闭建议使用html中的details元素的解决方法。

在实际使用之前,这可以用于某些用例。

---
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>
Run Code Online (Sandbox Code Playgroud)

在JSFiddle上尝试编织的HTML

  • OP 希望对_individual_块进行代码折叠,他们已经知道“code_folding”yaml选项 (4认同)

小智 5

随着rmarkdown版本2.3

基于7hibaut的回答,但不完全相同。当其他块已在 YAML 中class.source = "fold-show"隐藏时,请使用块标头中的选项来显示块,如rmarkdown 拉取请求中所述。code_folding: hide

    ---
    title: "Bohemian Rhapsody"
    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)
    ```

    ## Question 3

    suggested code

    ```{r class.source = "fold-show", eval = FALSE}
    library(dplyr)
    library(magrittr)
 
    a <- dMeasure::dMeasure$new()
    a$open_emr_db()
    ## active patients
    kensington_clinicians <- a$UserConfig %>>%
      filter(
        grepl(
          "Kensington",
          purrr::map_chr(Location, function(x) paste(x, collapse = ", "))
          # map_chr will create a 'collapsed' version of all the
          # listed locations
        )
    )
    ```
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述