Conditionally display a block of text in R Markdown

You need a complete R expression, so you cannot break it into multiple blocks like you show, but if the results of a block are a text string then it will be included as is (without quotes), so you should be able to do something like:

`r if(show.text){"la la la"}`

and it will include the text if and only if show.text is TRUE.


You can do this using the "eval" chunk option. See http://yihui.name/knitr/options/.

```{r setup, echo=FALSE}
show_text <- FALSE
````

```{r conditional_block, eval=show_text}
print("this will only print when show.text is TRUE")
```

I've been using YAML config files to parameterize my markdown reports which makes them more reusable.

```{r load_config}
library(yaml)
config <- yaml.load_file("config.yaml")
```

...

```{r conditional_print, eval=config$show_text}
print("la la la")
````

I find it easiest to do this by putting all of my text into a separate file and then include it from the main file with:

```{r conditional_print, child='text.Rmd', eval = show_text}
```

This has the advantage that you can still put inline R statements or other chunks into the child file, so that if you change your mind about what counts as optional text, you don't have to refactor your project.