【发布时间】:2016-02-23 23:06:15
【问题描述】:
我在 Rmd 文件中有一个标头,后跟一个代码块。如果满足条件,我只想包含此标头及其后面的块。我知道如何使用块来做到这一点,因为它在代码的主体中,但是我该如何做前者呢?
```{r}
print_option <- TRUE
```
## My header
```{r}
if(print_option==TRUE) {
print (x)
}
```
【问题讨论】:
我在 Rmd 文件中有一个标头,后跟一个代码块。如果满足条件,我只想包含此标头及其后面的块。我知道如何使用块来做到这一点,因为它在代码的主体中,但是我该如何做前者呢?
```{r}
print_option <- TRUE
```
## My header
```{r}
if(print_option==TRUE) {
print (x)
}
```
【问题讨论】:
chunk optioneval 和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 代码)engineasis 可能会有所帮助,请参阅this answer(它很长,但最后的解决方案非常简洁)。
为什么## `r Title` 和Title 设置为"My header" 或"" 如this answer 中所建议的那样是个坏主意?因为它在第二种情况下创建了一个“空标题”。此标头在呈现的 HTML/markdown 输出中不可见,但它仍然存在。请参阅以下示例:
```{r, echo = FALSE}
title <- ""
```
## `r title`
这会生成以下降价...
##
... 和 HTML:
<h2></h2>
除了语义上的废话外,它还可能导致布局问题(取决于样式表)并破坏文档大纲。
【讨论】:
cat 解决方案有什么问题?
print(1:10) 的输出格式,现在已修复。如果我误解了这个问题,请告诉我。
我想通了:)
```{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,它会给你留下一个“空标题”##。