Conditionally display a block of text in R Markdown

后端 未结 7 1964
一向
一向 2020-12-01 05:12

I am using knitr to parse an R Markdown document . Is there a way to conditionally display a block of text in R Markdown depending on a variable in the environment I pass i

7条回答
  •  被撕碎了的回忆
    2020-12-01 06:00

    The solutions above may be a little clunky for larger blocks of text and not great for certain situations. Let's say I want to create a worksheet for students with some questions and also use the same .Rmd file to generate a file with solutions. I used basic LaTeX flow control:

    ``` {r, include = F}
    # this can be e.g., in a parent .Rmd and the below can be in child
    solution <- TRUE 
    ```
    \newif\ifsol
    \sol`r ifelse(solution, 'true', 'false')`
    

    Then I can do:

    What is $2 + 2$
    
    \ifsol
    4
    \fi
    

    This way you can also create alternative blocks of text using

    \ifsol
    Alternative 1
    \else
    Alternative 2
    \fi
    

提交回复
热议问题