问题
I have a header followed by a code chunk in an Rmd file. I only want to include this header and the chunk followed by it, if a condition is met. I know how to do that with the chunk, since it's in the body of the code, but how do I do the former?
```{r}
print_option <- TRUE
```
## My header
```{r}
if(print_option==TRUE) {
print (x)
}
```
回答1:
The chunk option eval
and asis_output()
provide a simple solution.
Assuming that print_option
is a boolean indicating whether to show the header (and whether to execute other code like print(1:10)
in chunk example1
):
```{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")
```
Output:
For longer conditional outputs (of text/markdown, without embedded R code) the engine asis
can be helpful, see this answer (it's long, but the solution at the end is very concise).
Addendum
Why is ## `r Title`
with Title
set to "My header"
or ""
as suggested in this answer a bad idea? Because it creates an "empty header" in the second case. This header is not visible in the rendered HTML/markdown output, but it is still there. See the following example:
```{r, echo = FALSE}
title <- ""
```
## `r title`
This generates the following markdown ...
##
... and HTML:
<h2></h2>
Besids being semantically nonsense it might lead to layout issues (depending on the style sheet) and disrupts the document outline.
回答2:
I figured it out :)
```{r, echo=FALSE, include=FALSE}
x<- FALSE
if ( x ) {
Title <- "My header"
} else {Title=""}
```
## `r Title`
```{r, echo=FALSE}
if(x) {
print(1:10)
}
```
来源:https://stackoverflow.com/questions/35590023/how-to-include-a-header-based-on-a-condition-in-knitr