使用rmarkdown
准备报告时:http://rmarkdown.rstudio.com/人们可能希望文档根据文档类型以不同的方式呈现。例如,如果呈现的文档是html文件,我可能想嵌入一个youtube视频,而如果是pdf或MS Word,我会想要超链接的URL。
有没有一种方法可以告诉rmarkdown
这样的东西:
if (html) {
<iframe width="640" height="390" src="https://www.youtube.com/embed/FnblmZdTbYs? feature=player_detailpage" frameborder="0" allowfullscreen></iframe>
} else {
https://www.youtube.com/watch?v=ekBJgsfKnlw
}
代码
devtools::install_github("rstudio/rmarkdown")
library(rmarkdown)
render("foo.Rmd", "all")
foo.Rmd
---
title: "For Fun"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
toc: true
theme: journal
number_sections: true
pdf_document:
toc: true
number_sections: true
word_document:
fig_width: 5
fig_height: 5
fig_caption: true
---
## Good times
<iframe width="640" height="390" src="https://www.youtube.com/embed/FnblmZdTbYs?feature=player_detailpage" frameborder="0" allowfullscreen></iframe>
正如在回答相关问题时所指出的,knitr
1.18引入了以下函数
knitr::is_html_output()
knitr::is_latex_output()
顾名思义,is_html_output()
检查输出是否为HTML。你可以在foo.Rmd
:中添加这样的内容
```{r results='asis'}
if (knitr::is_html_output()) {
cat('<iframe width="640" height="390" src="https://www.youtube.com/embed/FnblmZdTbYs? feature=player_detailpage" frameborder="0" allowfullscreen></iframe>')
} else {
cat("https://www.youtube.com/watch?v=ekBJgsfKnlw")
}
```
是的,您可以通过knitr::opts_knit$get("rmarkdown.pandoc.to")
访问输出格式。这将返回一个具有目标输出格式的字符串。这里有一个例子:
---
title: "Untitled"
output: html_document
---
```{r}
library(knitr)
opts_knit$get("rmarkdown.pandoc.to")
```
这将返回"html"表示html_document,"docx"表示word_document和"latex"表示pdf_document。所以为了回答你的问题,你可以做一些类似的事情:
html <- knitr::opts_knit$get("rmarkdown.pandoc.to") == "html"
另一种方法,使用代码块选项。
获取文档开头的输出文件类型。
```{r, echo=FALSE}
out_type <- knitr::opts_knit$get("rmarkdown.pandoc.to")
```
然后,eval
代码块取决于文件类型:
```{r, results='asis', eval=(out_type=="html"), echo=FALSE}
cat('<iframe width="640" height="390"
src="https://www.youtube.com/embed/FnblmZdTbYs?feature=player_detailpage"
frameborder="0" allowfullscreen>
</iframe>')
```
```{r, results='asis', eval=(out_type!="html"), echo=FALSE}
cat('https://www.youtube.com/embed/FnblmZdTbYs?feature=player_detailpage')
```