在使用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>
发布于 2015-04-29 02:44:14
可以,您可以通过knitr::opts_knit$get("rmarkdown.pandoc.to")
访问输出格式。这将返回一个具有目标输出格式的字符串。下面是一个例子:
---
title: "Untitled"
output: html_document
---
```{r}
库(Knitr)
opts_knit$get("rmarkdown.pandoc.to")
这将为html_document返回"html“,为word_document返回"docx”,为pdf_document返回"latex“。因此,要回答您的问题,您可以这样做:
html <- knitr::opts_knit$get("rmarkdown.pandoc.to") == "html"
发布于 2018-08-24 06:19:27
正如所指出的,in an answer to a related question,knitr
1.18 introduced具有以下功能
knitr::is_html_output()
knitr::is_latex_output()
顾名思义,is_html_output()
检查输出是否是HTML。您可以向foo.Rmd
添加类似以下内容的内容
```{r results='asis'}
如果(knitr::is_html_output()) {
cat('<iframe width="640" height="390" src="https://www.youtube.com/embed/FnblmZdTbYs? feature=player_detailpage" frameborder="0" allowfullscreen></iframe>')
}否则{
cat("https://www.youtube.com/watch?v=ekBJgsfKnlw")
}
发布于 2021-12-27 21:26:31
另一种方式,使用代码块选项。
获取文档开头的输出文件类型。
```{r, echo=FALSE}
out_type <- knitr::opts_knit$get("rmarkdown.pandoc.to")
然后,根据文件类型对代码块执行eval
操作:
```{r, results='asis', eval=(out_type=="html"), echo=FALSE}
Height=(‘https://www.youtube.com/embed/FnblmZdTbYs?feature=player_detailpage'</a>)</div><pre><code></code></pre><div></div>
https://stackoverflow.com/questions/25528067
复制相似问题