有条件地使用.Rmd文件中的knitr评估标题

时间:2014-07-13 20:09:42

标签: r knitr

是否可以使用R Markdown和knitr有条件地评估代码块其相关标题?例如,如果eval_cellTRUE,则其标题包含,但如果eval_cellFALSE,则不包括

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

# Heading (would like to eval only if eval_cell is TRUE)
```{r eval = eval_cell}
summary(cars)
```

1 个答案:

答案 0 :(得分:7)

您可以将标题放在内联R表达式中:

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

# Heading (would like to eval only if eval_cell is TRUE)
```{r}
summary(cars)
```

然后在原始(父)文档中,您只需要

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

```{r child='child.Rmd', eval=eval_cell}
```