Conditionally display a block of text in R Markdown

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 into knitr?

For instance, something like:

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

Would print "la la la" in the resulting doc if show.text is true.


Solution 1:

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.

Solution 2:

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")
````