我在一个Rmd文件中有一个标题,后面跟着一段代码块。如果满足条件,我只想包括这个标题和它后面的代码块。我知道如何处理代码块,因为它在代码主体中,但是如何处理前面的标题呢?
```{r}
print_option <- TRUE
```
## My header
```{r}
if(print_option==TRUE) {
print (x)
}
```
chunk option 的 eval
和 asis_output()
提供了简单的解决方案。
假设 print_option
是一个布尔值,指示是否显示头部(以及是否在块 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")
```
输出:
对于更长的条件性输出(文本/标记语言,没有嵌入式 R 代码),引擎 asis
可以很有帮助,参见 这个答案(它很长,但最后的解决方案非常简洁)。
为什么像这个答案所建议的那样使用## `r 标题`
,其中标题设置为"My header"
或""
是一种不好的方法?因为在第二种情况下它会创建一个"空标题"。这个标题在呈现的 HTML/markdown 输出中是不可见的,但它仍然存在。请看下面的示例:
```{r, echo = FALSE}
title <- ""
```
## `r title`
这将生成以下标记...
##
...和HTML:<h2></h2>
除了语义上毫无意义外,它可能会导致布局问题(取决于样式表),并破坏文档大纲。
我想通了 :)
```{r, echo=FALSE, include=FALSE}
x<- FALSE
if ( x ) {
Title <- "My header"
} else {Title=""}
```
## `r Title`
```{r, echo=FALSE}
if(x) {
print(1:10)
}
```
x
不为 TRUE
,它会留下一个“空标题” ##
。 - CL.
print(1:10)
的输出格式,那么现在已经修复了。如果我误解了问题,请告诉我。 - CL.