问题描述
是否可以使用R Markdown和knitr
有条件地评估代码块及其关联的标题?例如,如果eval_cell
是TRUE
,则包括块及其,但如果eval_cell
是FALSE
,则不包括块.
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)
```
推荐答案
您可以将标题放入内联R表达式中:
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)
```
如果需要有条件地包含大量文本/代码,这将变得很麻烦,在这种情况下,建议您将它们放在单独的子文档中,例如child.Rmd
:
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}
```
这篇关于在.Rmd文件中使用Knitr有条件地评估标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!