ifelse 操作取决于 rmarkdown 中的文档类型 [英] ifelse action depending on document type in rmarkdown

查看:69
本文介绍了ifelse 操作取决于 rmarkdown 中的文档类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 rmarkdown 准备报告时:http://rmarkdown.rstudio.com/ 人们可能希望文档根据文档类型进行不同的呈现.例如,如果呈现的文档是一个 html 文件,我可能想要嵌入一个 youtube 视频,而如果它是 pdf 或 MS Word,我想要的是超链接的 URL.

When preparing reports using rmarkdown: http://rmarkdown.rstudio.com/ one may want the document to render differently depending upon the document type. For instance I may want to embed a youtube video if the document being rendered is an html file where as if it's pdf or MS Word I would want the hyper-linked URL instead.

有没有办法告诉 rmarkdown 像这样:

Is there a way to tell rmarkdown something like this:

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::opts_knit$get("rmarkdown.pandoc.to") 访问输出格式.这将返回一个具有目标输出格式的字符串.举个例子:

Yes, you can access the output format via knitr::opts_knit$get("rmarkdown.pandoc.to"). This will return a string with the target output format. Here's an example:

---
title: "Untitled"
output: html_document
---

```{r}
library(knitr)
opts_knit$get("rmarkdown.pandoc.to")
```

这为 html_document 返回html",为 word_document 返回docx",为 pdf_document 返回latex".因此,要回答您的问题,您可以执行以下操作:

This returns "html" for html_document, "docx" for word_document, and "latex" for pdf_document. So to answer your question you can do something like:

html <- knitr::opts_knit$get("rmarkdown.pandoc.to") == "html"

这篇关于ifelse 操作取决于 rmarkdown 中的文档类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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