Conditionally evaluate heading using knitr in .Rmd file

不羁岁月 提交于 2019-12-05 00:35:44

问题


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

回答1:


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}
```


来源:https://stackoverflow.com/questions/24726680/conditionally-evaluate-heading-using-knitr-in-rmd-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!