7

Is it possible to conditionally evaluate a code chunk and its associated heading using R Markdown and knitr? For example, if eval_cell is TRUE include the chunk and its heading, but don't include either 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)
```
matt_k
  • 4,139
  • 4
  • 27
  • 33
  • **If** it's not supported, then first `brew` a document with `<% ... %>` tags, or give a try to my [pander package](http://rapporter.github.io/pander/#brew-to-pandoc). – daroczig Jul 13 '14 at 20:26

1 Answers1

9

You can put the heading in an inline R expression:

```{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 need to be conditionally included, in which case you are recommended 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

```{r}
eval_cell = TRUE
```

```{r child='child.Rmd', eval=eval_cell}
```
Yihui Xie
  • 28,913
  • 23
  • 193
  • 419