B.2 R Markdown

得益于 R 和 Pandoc 的强大功能,你可以轻松地在 R Markdown 文档中进行计算,并将其转换为各种输出格式,包括 HTML/PDF/Word 文档、HTML5/Beamer 幻灯片、仪表板和网站等。一份 R Markdown 文档通常由 YAML 元数据(可选)和文档主体组成。我们在第 2 章中介绍了编写文档主体各个组件的语法,并将在本节详细解释 YAML 元数据。

R Markdown 的元数据可以写在文档的最开头,分别以三个短划线 --- 开头和结尾。YAML 元数据通常由冒号分隔的标签和值组成,例如:

---
title: "An R Markdown Document"
author: "Yihui Xie"
---

对于字符类型的取值,当不包含特殊字符时,你可以省略引号,但如果希望它们被解析为字符类型,则使用引号更为安全。

除字符类型外,另一种常见类型是逻辑类型。yestrue 都表示 true,no/false 都表示 false,例如:

link-citations: yes

元数据取值也可以是向量,并且有两种写入向量的方法。下面列出的两种方法是等价的

output: ["html_document", "word_document"]
output:
  - "html_document"
  - "word_document"

元数据取值也可以是键值对的列表,只需要将其额外缩进两个空格,例如:

output:
  bookdown::gitbook:
    split_by: "section"
    split_bib: no

忘记缩进是一个常见的错误。例如,下面的数据

output:
html_document:
toc: yes

实际上表示

output: null
html_document: null
toc: yes

而不是你期望的那样:

output:
  html_document:
    toc: yes

R Markdown 输出格式是在 YAML 元数据的 output 字段中指定的,你需要查阅 R 帮助页面以获得可以填写的选项,例如 ?rmarkdown::html_document?bookdown::gitbook。YAML 中其它大多数字段的含义可以在 Pandoc 文档中找到。

rmarkdown 软件包提供了这些 R Markdown 输出格式:

  • beamer_presentation
  • context_document
  • github_document
  • html_document
  • ioslides_presentation
  • latex_document
  • md_document
  • odt_document
  • pdf_document
  • powerpoint_presentation
  • rtf_document
  • slidy_presentation
  • word_document

在其他 R 包中还支持了更多的输出格式,包括 bookdowntufterticlesflexdashboardrevealjsrmdformats等。