Conditionally evaluate header using knitr in .Rmd file

Is it possible to conditionally evaluate a piece of code and a related header using R Markdown and knitr ? For example, if eval_cell is TRUE , include the chunk and its header, but do not enable it if eval_cell is FALSE .

 ```{r} eval_cell = TRUE ``` # Heading (would like to eval only if eval_cell is TRUE) ```{r eval = eval_cell} summary(cars) ``` 
+5
source share
1 answer

You can put the header in the inline expression of R:

 ```{r} eval_cell = TRUE ``` `r if (eval_cell) '# Heading (would like to eval only if eval_cell is TRUE)'` ```{r eval = eval_cell} summary(cars) ``` 

This will become cumbersome if you have large blocks of text / code that should be conditionally included, in which case you are advised to put them in a separate child document, say child.Rmd :

 # Heading (would like to eval only if eval_cell is TRUE) ```{r} summary(cars) ``` 

Then in the original (parent) document you just need to

 ```{r} eval_cell = TRUE ``` ```{r child='child.Rmd', eval=eval_cell} ``` 
+7
source

All Articles