Conditionally display a block of text in R Markdown

后端 未结 7 1954
一向
一向 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 05:59

    Here's a tweak to Paul Boardman's approach that gives proper markup in the output.

    ```{r setup, echo=FALSE}
    show_text <- FALSE
    ```
    
    ```{r conditional_block, echo=FALSE, results='asis', eval=show_text}
    cat("## Hey look, a heading!
    
    lorem ipsum dolor emet...")
    ```
    

    Even better, if we invoke the python engine to generate our output, we can use triple quoting to easily handle text that contains single or double quotes without needing to do anything fancy:

    ```{python, conditional_block_py, echo=FALSE, results='asis', eval=show_cond_text}
    print("""
    ## Still a heading
    
    Block of text with 'single quotes' and "double quotes"
    """)
    ```
    

提交回复
热议问题