有条件地将视频嵌入R-markdown(预定) [英] conditionally embed video in R-markdown (bookdown)

查看:43
本文介绍了有条件地将视频嵌入R-markdown(预定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只是将YouTube提供的HTML代码复制并粘贴到.Rmd文件中,则可以很好地用于gitbook输出.这是代码示例

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>

但是,我收到有关PDF和EPUB输出的错误消息.为了避免这种情况,我认为我可以使用条件编译,例如

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>
}
```

但是,这在RStudio编辑器中已经被删掉了,用于意外的令牌.这是怎么了有没有解决这个问题的方法?

However, this gets crossed out already in the RStudio editor for unexpected tokens. What is wrong here? Is there a way around this issue?

推荐答案

欢迎使用stackoverflow!

Welcome to stackoverflow!

  • 是的,条件编译是解决此问题的一种方法.为此,我们需要告诉knitr是否应评估代码块(以输出格式为条件).必须通过块选项 eval 而不是代码块内部指定.

  • 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.

请注意,R无法解析纯HTML代码.相反,您可以将HTML代码作为字符串传递给 cat()(将打印字符串),并使用块选项 results ='asis'告诉knitr包括结果.

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 option results = '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>'
)
```

请注意,我还设置了 echo = F ,以使代码不会显示在输出中.

Note that I've also set echo = F such that the code is not printed in the output.

有关编织器选项的更多信息,请参见Yihui出色的文档.

Fore more on knitr options, see Yihui's excellent documentation.

这篇关于有条件地将视频嵌入R-markdown(预定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆