Conditional `echo` (or eval or include) in rmarkdown chunks

后端 未结 2 974
梦谈多话
梦谈多话 2020-12-09 04:22

I would like to create an Rmarkdown document (pdf or html) that has some chunks \"executed\" conditionally. The particular case I have in mind is that I might want a more v

相关标签:
2条回答
  • 2020-12-09 04:27

    opts_chunk$set() is what you are after. Anything "set" will be the default for subsequent chunks (unless overwritten on a chunk-by-chunk basis)

    ```{r setup}
    library(knitr)
    opts_chunk$set(eval = TRUE, include= TRUE)
    ````
    

    You can then alter as you see fit.

    0 讨论(0)
  • 2020-12-09 04:38

    knitr options can be stated as R expressions. Per the "output" documentation on the knitr webpage:

    Note all options in knitr can take values from R expressions, which brings the feature of conditional evaluation introduced in the main manual. In short, eval=dothis means the real value of eval is taken from a variable named dothis in the global environment; by manipulating this variable, we can turn on/off the evaluation of a batch of chunks.

    In other words if you write some chunks like:

    ```{r label}
    doNextChunk <- as.logical(rbinom(1,1,.5))
    ```
    
    ```{r conditional, eval = doNextChunk}
    "hello world!"
    ```
    
    0 讨论(0)
提交回复
热议问题