Conditionally display block of markdown text using knitr

前端 未结 2 1371
野的像风
野的像风 2020-12-13 21:22

I would like to edit a single rmarkdown (Rmd) document with a list of \"problems\", each followed by its solution. Each solution may contain the results of R console, but al

2条回答
  •  情书的邮戳
    2020-12-13 22:09

    There is a way to hide parts of the document (including text and chunks): to comment them out with html comment marks.

    And comment marks can be generated by R in a block according to a variable that can be set at the beginning of the document.

    ```{r results='asis', echo=FALSE}
    if (hide) {cat("")}
    ```
    

    And just to show a complete working example, in the example below the middle section of the document can be shown or hidden by setting the hide variable to FALSE or TRUE. That might be useful in case there are several sections to hide or show at once - for example, solutions of course problems.

    ---
    title: "Untitled"
    date: "15/10/2020"
    output:
      word_document: default
      html_document: default
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    hide <- TRUE #TRUE to comment out part of the document, FALSE to show.
    ```
    
    ## Start
    
    Always shown.
    
    ```{r}
    hide
    ```
    
    ```{r results='asis', echo=FALSE}
    if (hide) {cat("")}
    ```
    
    
    
    ## End
    
    Always shown.
    

提交回复
热议问题