如何根据 knitr 中的条件包含 header

How to include a header based on a condition in knitr

我有一个 header 后跟一个 Rmd 文件中的代码块。如果满足条件,我只想包括这个 header 和它后面的块。我知道如何处理块,因为它在代码的 body 中,但我如何处理前者?

```{r}
 print_option <- TRUE
```

## My header
```{r}
 if(print_option==TRUE) {
 print (x)
 }
```

我想通了:)

    ```{r, echo=FALSE,  include=FALSE}
    x<- FALSE
    if ( x ) {
      Title <- "My header"
    } else {Title=""}
    ```
    ## `r Title` 
    ```{r, echo=FALSE}
    if(x) {
    print(1:10)
    }
    ```

chunk option evalasis_output() 提供了一个简单的解决方案。

假设print_option是一个布尔值,指示是否显示header(以及是否在块example1中执行其他代码,如print(1:10)):

```{r setup}
library(knitr)
print_option <- TRUE
```

```{r, eval = print_option}
asis_output("## My header\n") # Header that is only shown if print_option == TRUE
print(1:10) # Other stuff that is only executed if print_option == TRUE
```

Text that is shown regardless of `print_option`.

```{r setup2}
print_option <- FALSE
```

Now `print_option` is `FALSE`. Thus, the second header is not shown.

```{r, eval = print_option}
asis_out("## Second header\n")
```

输出:

对于较长的条件输出(text/markdown,没有嵌入式 R 代码)engine asis can be helpful, see this answer(很长,但最后的解决方案非常简洁)。

附录

为什么 ## `r Title`Title 设置为 "My header""",如 this answer 中建议的那样是个坏主意?因为它在第二种情况下创建了一个 "empty header" 。 header 在呈现的 HTML/markdown 输出中 不可见 ,但它仍然存在。请参阅以下示例:

```{r, echo = FALSE}
title <- ""
```

## `r title`

这会生成以下降价...

## 

... 和 HTML:

<h2></h2>

除了在语义上毫无意义之外,它还可能导致布局问题(取决于样式 sheet)并扰乱文档大纲。