有条件的RMarkdown文档的编块

时间:2019-07-16 15:15:22

标签: r rstudio r-markdown

我有一个带有多个块的RMarkdown文档。这些块中的一些仅在文档类型为A时显示,其他块仅在文档类型为B时才显示。其他块是相同的,每次编织文档时都应出现。因此:

```{r common_chunk}
output_common <- "This is a common chunk. It should always show up"
```
```{r A_chunk}
output_A <- "This chunk is type A."
```
```{r B_chunk}
output_B <- "This chunk is type B. If you see this at the same time you see a type A chunk, something is coded wrong."
```

我该如何精确编码,使其以我想要的方式编织? RMarkdown文档中有一个带有全局if语句的示例...

```{r}
# execute code if the date is later than a specified day
do_it = Sys.Date() > '2018-02-14'
```

```{r, eval=do_it}
x = rnorm(100)
```

...但是当我尝试将这种逻辑应用于我的代码时...

toggle <- "A"
```{r A_chunk, eval = ifelse(toggle == "A")}
output_A <- "This chunk is type A."
```

...我收到一个错误,说argument "no" is missing, with no default。有人可以告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

问题是我原来使用ifelse的方法。这段代码有效:

```{r toggle}
toggle <- "A"
```
```{r common_chunk}
output_common <- "This is a common chunk. It should always show up"
```
```{r A_chunk, eval = (toggle == "A")}
output_A <- "This chunk is type A."
```
```{r B_chunk, eval = (toggle == "B")}
output_B <- "This chunk is type B. If you see this at the same time you 
see a type A chunk, something is coded wrong."
```