问题
If I simply copy and paste an HTML code provided by YouTube into a .Rmd file, this works fine for gitbook output. Here is an example of the code
<iframe width="560" height="315" src="https://www.youtube.com/embed/9AI3BkKQhn0"
frameborder="0" allow="accelerometer; autoplay; encrypted-media;
gyroscope; picture-in-picture" allowfullscreen>
</iframe>
However, I get error messages for PDF and EPUB outputs. In order to avoid this, I thought I could use conditional compilation, e.g.
```{r}
if (knitr::is_html_output(excludes = "epub")) {
<iframe width="560" height="315"
src="https://www.youtube.com/embed/9AI3BkKQhn0"
frameborder="0" allow="accelerometer; autoplay; encrypted-media;
gyroscope; picture-in-picture" allowfullscreen>
</iframe>
}
```
However, this gets crossed out already in the RStudio editor for unexpected tokens. What is wrong here? Is there a way around this issue?
回答1:
Welcome to stackoverflow!
You are right, conditional compilation is a way to solve this. For this, we need to tell knitr whether the code chunk should be evaluated (conditional on the output format). This must be specified via the chunk option
eval
, not inside the code chunk.Note that R cannot parse plain HTML code. Instead, you could pass HTML code as a string to
cat()
(which prints the string) and tell knitr to include the results using the chunk optionresults = 'asis'
.
```{r, eval=knitr::is_html_output(excludes = "epub"), results = 'asis', echo = F}
cat(
'<iframe width="560" height="315"
src="https://www.youtube.com/embed/9AI3BkKQhn0"
frameborder="0" allow="accelerometer; autoplay; encrypted-media;
gyroscope; picture-in-picture" allowfullscreen>
</iframe>'
)
```
Note that I've also set echo = F
such that the code is not printed in the output.
Fore more on knitr options, see Yihui's excellent documentation.
来源:https://stackoverflow.com/questions/63354509/conditionally-embed-video-in-r-markdown-bookdown