knitr::opts_chunk$set(collapse = TRUE,fig.align = "center")

1 安装

# install.packages("rmarkdown")
# update.packages("rmarkdown")

如果想生成PDF输出,需要安装LaTeX。对于之前没有安装LaTeXMarkdown用户,我们建议您安装TinyTeX (https://yihui.name/tinytex/):

# install.packages("tinytex")
# tinytex::install_tinytex()  # install TinyTeX

TinyTeX是一种轻量级、便携、跨平台且易于维护的LaTeX发行版。 在将LaTeX或R标记文档编译为PDF时,R包tinytex可以帮助您自动安装缺少的LaTeX包, 还可以确保将LaTeX文档编译正确的次数,以解析所有交叉引用。如果您不理解这两件事的含义, 您可能应该按照我们的建议安装TinyTeX,因为这些细节通常不值得您花费时间或精力。

使用RMarkdown包、RStudio/PandocLaTeX,您应该能够编译大多数RMarkdown文档。

2 RMarkdown基础知识

RMarkdown的设计是为了更容易可重复性,因为计算代码和说明都在同一个文档中,并且结果自动从源代码生成。RMarkdown支持数十种静态和动态/交互输出格式

下面是一个最小的R标记文档,它应该是一个纯文本文件,扩展名为.Rmd:

# ---
title: "Hello R Markdown"   
author: "Awesome Me"
date: "2018-02-14"
output: html_document       # 重要
# ---

代码块

fit = lm(dist ~ speed, data = cars)
b   = coef(fit)
plot(cars)
abline(fit)

回归的截距是:-17.5790949.

2.2 编译一个RMarkdown文件

rmarkdown::render("第一章安装.Rm")

You can render it to PDF via:

rmarkdown::render('第一章安装.Rmd')

使用notebook,您可以单独运行代码块,并在RStudio编辑器中查看结果。这是与Rmd文档中的代码进行交互或实验的一种方便的方法,因为您不必编译整个文档。不使用notebook,您仍然可以部分地执行代码块,但是执行只发生在R控制台,并且notebook接口在编辑器的代码块下面显示代码块的结果,这是一个很大的优势。同样,为了可重复性,您需要最终在一个干净的环境中编译整个文档

2.3 速查表

RStudio创建了大量备忘单,包括单页的RMarkdown速查表,这些速查表可以在https://www.rstudio.com/resources/cheatsheets/ 免费获得 。还有一个更详细的RMarkdown参考指南。这两个文档都可以在您熟悉RMarkdown之后用作快速引用。

2.4 RMarkdown输出格式

rmarkdown包中有两种类型的输出格式:文档和演示文稿。所有可用的格式如下:

  • beamer_presentation

  • github_document

  • html_document

  • ioslides_presentation

  • latex_document

  • md_document

  • odt_document

  • pdf_document

  • powerpoint_presentation

  • rtf_document

  • slidy_presentation

  • word_document

对于Rmd文件的YAML元数据中的输出格式名,如果格式来自扩展包,则需要包含包名, 例如,output: tufte::tufte_html,如果格式来自rmarkdown 包,则不需要使用rmarkdown::

每种输出格式通常都伴随着几个格式选项。所有这些选项都记录在R包帮助页面上。例如,您可以在R中键入?rmarkdown::html_document来打开html_document格式的帮助页面。当你想使用某些选项时,你必须将值从R转换为YAML,例如,

html_document(toc = TRUE, toc_depth = 2, dev = 'svg')需要写成

output: html_document: toc: true toc_depth: 2 dev: 'svg'

YAML中的字符串通常不需要引号 除非它们包含特殊字符,例如冒号:。如果您不确定是否应该引用字符串,可以使用yaml包测试它,例如

cat(yaml::as.yaml(list(
  title = 'A Wonderful Day',
  subtitle = 'hygge: a quality of coziness'
)))
title: A Wonderful Day
subtitle: 'hygge: a quality of coziness'

如果您有需要作为评估R表达式的结果的选项,您可以使用!expr,它告诉yaml包它需要解析和评估这个选项。 下面是一个为HTML输出使用随机主题的例子:

output:
  html_document:
    theme: !expr sample(c("yeti", "united", "lumen"), 1)
output:
  html_document:
    toc: true
    includes:
      in_header: header.html
      before_body: before.html

RMarkdown输出格式函数通常有一个pandoc_args参数,它应该是要传递给Pandoc的额外参数的字符向量。如果您发现任何Pandoc特性没有由输出格式参数表示,您可以使用这个最终参数,例如,

output:
  pdf_document:
    toc: true
    pandoc_args: ["--wrap=none", "--top-level-division=chapter"]

2.5 Markdown语法

可以在https://pandoc.org/MANUAL.html 上找到Pandoc的Markdown的完整文档。我们强烈建议您至少阅读本页面 一次,以了解Pandoc的Markdown的所有可能性

2.5.1 内联格式

```code```, which is rendered as code. Hyperlinks are created using the syntax text, 例如: RStudio

# 图像 ![alt text or image title](path/to/image)

Footnotes are put inside the square brackets after a caret 1, 例如: 2.

2.5.2 级别元素

# First-level header

## Second-level header

### Third-level header

如果你不想给某个标题加入文字,可以在标题后加入{-}或者 {.unnumbered},例如:# Preface {-}

您可以通过缩进子列表来将一个列表嵌套到另一个列表中(缩进4),例如,

  • one item

  • one item

  • one item

    • one more item

    • one more item

    • one more item

  1. the first item

  2. the second item

  3. the third item

    • one unordered item

    • one unordered item

引用的用法,例如

“I thoroughly disapprove of duels. If a man should challenge me, I would take him kindly and forgivingly by the hand and lead him to a quiet place and kill him.”

— Mark Twain

输出为:

# “I thoroughly disapprove of duels. If a man should challenge me, I would take him kindly and forgivingly by the hand and lead him to a quiet place and kill him.”

#                                                                                                                 — Mark Twain

一般来说,你最好在相邻但不同的元素之间至少留一行空,例如,标题和段落。这是为了避免Markdown呈现模糊性。如果没有空行,不同风格的RMarkdown可能会产生不同的结果。

2.5.3 数学表达式

内联LaTeX方程可以用LaTeX语法写成一对美元符号,例如:\(f(k) = {n \choose k} p^{k} (1-p)^{n-k}\) 或者表示为:\[f(k) = {n \choose k} p^{k} (1-p)^{n-k}\]

几个例子:

\[\begin{array}{ccc} x_{11} & x_{12} & x_{13}\\ x_{21} & x_{22} & x_{23} \end{array}\]

\[X = \begin{bmatrix}1 & x_{1}\\ 1 & x_{2}\\ 1 & x_{3} \end{bmatrix}\]

\[\Theta = \begin{pmatrix}\alpha & \beta\\ \gamma & \delta \end{pmatrix}\]

\[\begin{vmatrix}a & b\\ c & d \end{vmatrix}=ad-bc\]

2.6 代码块和内联R代码

  • 代码块快捷键(Ctrl + Alt + I (Cmd + Option + I on macOS).)

  • 隐藏文本输出:results = ‘hide’,设置高度:fig.height = 4 例如:```{r, chunk-label, results=‘hide’, fig.height=4}

在代码块中有很多的参数,详见https://yihui.name/knitr/options。 我们列出其中重要的一部分,如下(英文):

  • eval: Whether to evaluate a code chunk.

  • echo: Whether to echo the source code in the output document (someone may not prefer reading your smart source code but only results).

  • results: When set to ‘hide’, text output will be hidden; when set to ‘asis’, text output is written “as-is”, e.g., you can write out raw Markdown text from R code (like cat(‘Markdown is cool.’)). By default, text output will be wrapped in verbatim elements (typically plain code blocks).

  • collapse: Whether to merge text output and source code into a single code block in the output. This is mostly cosmetic: collapse = TRUE makes the output more compact, since the R source code and its text output are displayed in a single output block. The default collapse = FALSE means R expressions and their text output are separated into different blocks.

  • warning, message, and error: Whether to show warnings, messages, and errors in the output document. Note that if you set error = FALSE, rmarkdown::render() will halt on error in a code chunk, and the error will be displayed in the R console. Similarly, when warning = FALSE or message = FALSE, these messages will be shown in the R console.

  • include: Whether to include anything from a code chunk in the output document. When include = FALSE, this whole code chunk is excluded in the output, but note that it will still be evaluated if eval = TRUE. When you are trying to set echo = FALSE, results = ‘hide’, warning = FALSE, and message = FALSE, chances are you simply mean a single option include = FALSE instead of suppressing different types of text output individually.

  • cache: Whether to enable caching. If caching is enabled, the same code chunk will not be evaluated the next time the document is compiled (if the code chunk was not modified), which can save you time. However, I want to honestly remind you of the two hard problems in computer science (via Phil Karlton): naming things, and cache invalidation. Caching can be handy but also tricky sometimes.

  • fig.width and fig.height: The (graphical device) size of R plots in inches. R plots in code chunks are first recorded via a graphical device in knitr, and then written out to files. You can also specify the two options together in a single chunk option fig.dim, e.g., fig.dim = c(6, 4) means fig.width = 6 and fig.height = 4.

  • out.width and out.height: The output size of R plots in the output document. These options may scale images. You can use percentages, e.g., out.width = ‘80%’ means 80% of the page width.

  • fig.align: The alignment of plots. It can be 'left', 'center', or 'right'.

  • dev: The graphical device to record R plots. Typically it is 'pdf' for LaTeX output, and 'png' for HTML output, but you can certainly use other devices, such as 'svg' or 'jpeg'.

  • fig.cap: The figure caption.

  • child: You can include a child document in the main document. This option takes a path to an external file.

如果需要在多个代码块中频繁地将某个选项设置为某个值,可以考虑在文档的第一个代码块中全局设置该选项。

2.6.1 图像

要从同一个代码块并排放置多个图形,可以使用fig.show=’hold’选项和out.width选项。

par(mar = c(4, 4, 0.2, 0.1))
plot(cars, pch = 19)
plot(pressure, pch = 17)

如果你想要包括一个图形,不是从R生成代码,你可以用knitr::include_graphics()函数

# knitr::include_graphics('D:\\R_Book\\Xie_Rmarkdown\\hex-rmarkdown.png')

2.6.2 表格

包含表的最简单方法是使用knitr::kable(),它可以为HTML、PDF和Word输出创建表。通过将标题传递给函数,可以包含3个表标题,例如:

knitr::kable(iris[1:5, ], caption = 'A caption')
A caption
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa

非latex输出格式的表总是放在代码块之后。对于LaTeX/PDF输出格式,表具有与图相同的问题:它们可能会浮动。 当您必须考虑不同的输出格式时,情况会更加复杂。例如,很难使复杂的表同时适用于PDF和HTML输出。我们知道这是令人失望的,但有时您可能不得不考虑其他表示数据的方法,比如使用图形。

2.7 其它语言

names(knitr::knit_engines$get())
##  [1] "awk"       "bash"      "coffee"    "gawk"      "groovy"   
##  [6] "haskell"   "lein"      "mysql"     "node"      "octave"   
## [11] "perl"      "psql"      "Rscript"   "ruby"      "sas"      
## [16] "scala"     "sed"       "sh"        "stata"     "zsh"      
## [21] "highlight" "Rcpp"      "tikz"      "dot"       "c"        
## [26] "fortran"   "fortran95" "asy"       "cat"       "asis"     
## [31] "stan"      "block"     "block2"    "js"        "css"      
## [36] "sql"       "go"        "python"    "julia"     "sass"     
## [41] "scss"
# install.packages("reticulate")
library(reticulate)
x = 'hello, python world!'
print(x.split(' '))

2.8 交互式文档

2.8.1 HTML widgets

访问https://www.htmlwidgets.org 了解更多关于widget包的信息,以及如何自己开发widget包。

library(leaflet)
leaflet() %>% 
  addTiles() %>% 
  setView(119.36,39.9,zoom = 6) %>% 
  addMarkers(lng = 119.36,lat = 39.9,popup = "秦皇岛")

2.8.2 Shiny documents

一个标准的R绘图可以通过将它包装在闪亮的renderPlot()函数中来实现交互。selectInput()函数的作用是:创建输入小部件来驱动绘图。

HTML widgets和shiny依赖于HTML和JavaScript。它们能够以任何RMarkdown格式工作,并可以在浏览器中查看,比如HTML文档、dashboards和HTML5。

3 文档

Pandoc极大地扩展了Markdown语法。此外,Pandoc使将标记文档转换为多种输出格式成为可能。 在本章中,我们将介绍各种文档输出格式的特性。在接下来的两章中,我们将分别记录表示格式和其他RMarkdown扩展。

3.1 HTML文档

要从RMarkdown创建HTML文档,需要在文档的YAML元数据中指定html_document输出格式:

3.1.1 Table of contents

您可以使用TOC选项添加一个目录(TOC),并使用toc_depth选项指定它应用于的头的深度。

3.1.1.1 Floating TOC

您可以指定toc_float选项来将内容表浮动到主文档内容的左侧。即使在滚动文档时,浮动的目录也总是可见的。例如:

---
title: "Habits"
output:
  html_document:
    toc: true
    toc_float:
      collapsed: false
      smooth_scroll: false
---

3.1.2 节编号

---
title: "Habits"
output:
  html_document:
    toc: true
    number_sections: true
---

3.1.3 标签部分

您可以通过将.tabset类属性应用于文档中的标题来使用选项卡组织内容。 这将导致带有.tabset属性的标头的所有子标头出现在选项卡中,而不是作为单独的部分。例如:

## Quarterly Results {.tabset}

### By Product

(tab content)

### By Region

(tab content)

您还可以指定两个附加属性来控制选项卡的外观和行为。.tabset-fade属性使选项卡在选项卡之间切换时淡入和淡出。.tabset-pill属性使选项卡的视觉外观成为“pill”

3.1.4 外观和风格

highlight 指定语法突出显示样式

---
title: "Habits"
output:
  html_document:
    theme: united
    highlight: tango
---

3.1.4.1 自定义css

您可以使用CSS选项将自己的CSS添加到HTML文档中:

---
title: "Habits"
output:
  html_document:
    css: styles.css
---

如果你想从你自己的CSS中为文档提供所有的样式,你可以将theme(和可能的highlight显示)设置为null:

---
title: "Habits"
output:
  html_document:
    theme: null
    highlight: null
    css: styles.css
---

还可以使用自定义CSS将id或类添加到文档中的节标头中,从而针对文档的特定节。

## Next Steps {#nextsteps .emphasized}

将使您能够应用CSS的所有内容使用以下CSS选择器之一:

#nextsteps {
   color: blue;
}

.emphasized {
   font-size: 1.2em;
}

3.1.5 图选项

fig_retina: 指定要为视网膜显示器执行的缩放(默认为2,目前适用于所有广泛使用的视网膜显示器)。设置为空,以防止视网膜结垢。

例如:

---
title: "Habits"
output:
  html_document:
    fig_width: 7
    fig_height: 6
    fig_caption: true
---

3.1.6 数据帧输出

3.6.1.1 分页输出

---
title: "Motor Trend Car Road Tests"
output:
  html_document:
    df_print: paged
---

# ```{r}
# mtcars
# ```

分页HTML表的选项

  • Option         Description

  • max.print        The number of rows to print.

  • rows.print       The number of rows to display.

  • cols.print       The number of columns to display.

  • cols.min.print     The minimum number of columns to display.

  • pages.print       The number of pages to display under page navigation.

  • paged.print       When set to FALSE turns off paged tables.

  • rownames.print     When set to FALSE turns off row names.

# ```{r cols.print=3, rows.print=3}
# mtcars
# ```

3.1.7 隐藏代码

---
title: "Habits"
output:
  html_document:
    code_folding: hide
---

3.1.8 MathJax方程

默认情况下,MathJax脚本包含在HTML文档中,用于呈现LaTeX和MathML方程。您可以使用mathjax选项来控制如何包含mathjax:

例如: use a local copy of MathJax:

---
title: "Habits"
output:
  html_document:
    mathjax: local
    self_contained: false
---

use a self-hosted copy of MathJax:

---
title: "Habits"
output:
  html_document:
    mathjax: "http://example.com/MathJax.js"
---

To exclude MathJax entirely:

---
title: "Habits"
output:
  html_document:
    mathjax: null
---

3.1.9 文档依赖性

默认情况下,R Markdown使用没有外部依赖的独立HTML文件,使用数据:uri将包含链接脚本、样式表、图像和视频的内容。 这意味着你可以分享或发布文件,就像你共享办公室文件或pdf文件一样。如果您宁愿在外部文件中保持依赖项,则可以指定self_contained: false

---
title: "Habits"
output:
  html_document:
    self_contained: false
---

注意,即使对于自包含的文档,MathJax仍然是在外部加载的(这是必要的,因为它的大小很大)。 如果希望在本地提供MathJax,应该指定 mathjax: localself_contained: false.

将依赖项放在外部的一个常见原因是为了从网站上提供RMarkdown文档(外部依赖项可以由浏览器单独缓存,从而加快页面加载时间)。 在提供多个R标记文档的情况下,您可能还希望将依赖的库文件(例如Bootstrap和MathJax等)合并到多个文档共享的单个目录中。

---
title: "Habits"
output:
  html_document:
    self_contained: false
    lib_dir: libs
---

3.1.10 高级自定义

3.1.10.1 Keeping Markdown

当knitr处理一个RMarkdown输入文件时,它创建一个**Markdown(*.md)文件,该文件随后被Pandoc转换成HTML。如果你想在渲染后 保留一个标记文件的副本,你可以使用keep_md选项**:

---
title: "Habits"
output:
  html_document:
    keep_md: true
---

3.1.10.2 includes选项

例如:

---
title: "Habits"
output:
  html_document:
    includes:
      in_header: header.html
      before_body: doc_prefix.html
      after_body: doc_suffix.html
---

3.1.10.3 自定义模板

---
title: "Habits"
output:
  html_document:
    template: quarterly_report.html
---

有关模板的更多详细信息,请参阅关于Pandoc模板的文档。 还可以研究默认的HTML模板默认值

3.1.10.4 Markdown extensions

您可以使用md_extensions选项启用或禁用Markdown扩展(在选项前加上- to disable和+ to enable)。例如:

---
title: "Habits"
output:
  html_document:
    md_extensions: -autolink_bare_uris+hard_line_breaks
---

3.1.10.5 Pandoc参数

如果您想使用Pandoc特性,但是在上面描述的YAML选项中缺少相应的特性,那么您仍然可以通过传递定制的pandoc_args来使用它们。例如:

---
title: "Habits"
output:
  html_document:
    pandoc_args: [
      "--title-prefix", "Foo",
      "--id-prefix", "Bar"
    ]
---

3.1.11 Shared 选项

如果希望指定一组默认选项,以便由目录中的多个文档共享,可以包含一个名为**_output.yml**的文件。注意,这个文件中没有使用YAML分隔符(——)或封闭的output字段。例如:

html_document:
  self_contained: false
  theme: united
  highlight: textmate
---
output:
  html_document:
    self_contained: false
    theme: united
    highlight: textmate
---

3.1.12 HTML 片段

如果想创建HTML片段而不是完整的HTML文档,可以使用html_fragment格式。例如: output: html_fragment

注意,HTML片段不是完整的HTML文档。它们不包含HTML文档所包含的标准头内容(它们只包含普通HTML文档的

标记中的内容)。 它们用于包含在其他web页面或内容管理系统(如博客)中。因此,它们不支持主题或代码突出显示之类的特性

3.2 Notebook

任何RMarkdown文档都可以用作笔记本(Notebook),并且所有R笔记本都可以呈现为其他RMarkdown文档类型。 因此,笔记本可以被认为是R标记文档的一种特殊执行模式。记事本模式的即时性使得它在编写R标记文档和迭代代码时是一个很好的选择。 当您准备发布文档时,您可以直接共享该记事本,或者使用Knit按钮将其呈现为发布格式。

3.2.1 使用Notebook

3.2.1.1 创建笔记本

3.2.1.2 插入代码块

快捷键:

  • Ctrl + Alt + I 可以快速插入代码块

  • Ctrl + Shift + Enter 执行代码块

  • Ctrl + Enter (macOS: Cmd + Enter)运行当前语句

3.1.1.3 执行代码块

3.1.1.4 代码块输出

html_notebookYAML元数据中最顶层(默认)格式时,您将在编辑器工具栏中看到一个预览按钮。单击它将显示Notebook预览

如果您配置了RMarkdown预览来使用Viewer窗格,那么无论何时保存笔记本,预览都会自动更新。

在大多数情况下,在使用笔记本时不应该打开控制台,因为您可以在笔记本中看到所有控制台输出。为了保持垂直空间,当您打开笔记本或在笔记本中运行一个块时,控制台将自动折叠。

3.2.2 Saving and sharing

3.2.2.1 Notebook file

3.2.2.2 输出存储

3.2.2.3 版本控制

3.2.3 Notebook 格式

3.2.3.1 Generating R Notebooks with custom output

3.2.3.2 Implementing output sources

3.2.3.3 Parsing R Notebooks

3.3 pdf 文档

---
title: "Habits"
author: John Doe
date: March 22, 2005
output: pdf_document
---

3.3.1 目录

---
title: "Habits"
output:
  pdf_document:
    toc: true
    toc_depth: 2
---
---
title: "Habits"
output:
  pdf_document:
    toc: true
    number_sections: true
---

3.3.2 图选项

  • fig_width和fig_height: 可用于控制默认图形的宽度和高度(默认情况下6x4.5)。

  • fig_crop: 控制pdfcrop实用程序(如果在系统中可用)是否自动应用于PDF图形(默认情况下为真)。

  • fig_title: 控制是否使用标题呈现图形(默认情况下为false)。

  • dev: 控制用于呈现图形的图形设备(默认为pdf)。

例如:

---
title: "Habits"
output:
  pdf_document:
    fig_width: 7
    fig_height: 6
    fig_caption: true
---

3.3.3 数据帧输出

---
title: "Habits"
output:
  pdf_document:
    df_print: kable
---

3.3.4 语法高亮显示

---
title: "Habits"
output:
  pdf_document:
    highlight: tango
---

3.3.5 LaTeX选项

用于创建PDF文档的LaTeX模板的许多方面都可以使用YAML元数据进行定制(注意,这些选项不会出现在输出部分的下面,而是出现在顶层,以及标题、作者等)。例如:

---
title: "Crop Analysis Q3 2013"
output: pdf_document
fontsize: 11pt
geometry: margin=1in
---

可用于LaTeX输出的顶级YAML元数据变量,详见[网址]https://bookdown.org/yihui/rmarkdown/pdf-document.html

3.3.6 LaTeX packages for citations

默认情况下,引用是通过pandoc-citeproc处理的,它适用于所有输出格式。对于PDF输出,有时使用Latex包处理引用会更好,比如natbibbiblatex。要使用其中一个包,只需将选项citation_package设置为natbib或biblatex,例如。

---
output:
  pdf_document:
    citation_package: natbib
---

3.3.7 高级自定义

3.3.7.1 Latex engine

pdflatex, xelatex, and lualatex

---
title: "Habits"
output:
  pdf_document:
    latex_engine: xelatex
---

3.3.7.2 保留tex

首先将R标记文档转换为TeX文件,然后调用LaTeX引擎将其转换为PDF。默认情况下,这个TeX文件将被删除,但是如果您想保留它(例如,对于提交的文章),您可以指定keep_tex选项。例如:

---
title: "Habits"
output:
  pdf_document:
    keep_tex: true
---

3.3.7.3 Includes

通过包含额外的LaTeX指令和/或内容,或者完全替换核心的Pandoc模板,您可以对PDF输出进行更高级的定制。要在文档头部或文档主体之前/之后包含内容,可以使用include选项,如下所示:

---
title: "Habits"
output:
  pdf_document:
    includes:
      in_header: preamble.tex
      before_body: doc-prefix.tex
      after_body: doc-suffix.tex
---

3.3.7.4 自定义模板

---
title: "Habits"
output:
  pdf_document:
    template: quarterly-report.tex
---

有关模板的更多详细信息,请参阅关于[Pandoc模板的文档]https://pandoc.org/README.html#templates

3.3.8 其他特点

3.4 word文档

---
title: "Habits"
author: John Doe
date: March 22, 2005
output: word_document
---

Word文档最显著的特征是Word模板,也称为“style reference document”。您可以指定一个文档作为样式引用,用于生成.docx文件(Word文档)。这将允许您自定义诸如页边距和其他格式特征等内容。为了获得最佳结果,参考文档应该是使用rmarkdown或Pandoc生成的.docx文件的修改版本。

这样一个文档的路径可以传递到word_document格式的reference_docx参数。传递“default”以使用默认样式。例如:

---
title: "Habits"
output:
  word_document:
    reference_docx: my-styles.docx
---

详细内容阅读文章

3.4.1 其它特点

Word文档的大部分特性的文档, 包括figure options(3.1.5)data frame printing(3.1.6)syntax highlight(3.1.4)keeping Markdown(3.1.10.1)Markdown扩展(3.1.10.4)Pandoc arguments(3.1.10.5)shared options(3.1.11)

3.3.7.4 自定义模板

---
  title: "Habits"
output:
  pdf_document:
  template: quarterly-report.tex
---

有关模板的更多详细信息,请参阅关于[Pandoc模板的文档] (https://pandoc.org/README.html#templates)。

3.3.8 其他特点

3.4 word文档

---
title: "Habits"
author: John Doe
date: March 22, 2005
output: word_document
---

3.4.1 其它特点

Word文档的大部分特性的文档,包括figure options(3.1.5)data frame printing(3.1.6)syntax highlight(3.1.4)keeping Markdown(3.1.10.1)Markdown扩展(3.1.10.4)Pandoc arguments(3.1.10.5)shared options(3.1.11)

3.5 OpenDocument Text 文档

---
title: "Habits"
output:
  odt_document:
    reference_odt: my-styles.odt
---

3.5.1 其它特点

3.6 富文本格式文档

要从R Markdown创建富文本格式(RTF)文档,请在文档的YAML元数据中指定rtf_document输出格式:

---
title: "Habits"
author: John Doe
date: March 22, 2005
output: rtf_document
---

如果您非常熟悉RTF格式,那么实际上可以将原始RTF内容嵌入到RMarkdown中。例如, 您可以使用其他软件包在RTF中创建一个表,并将其插入到最终的RTF输出文档中。RTF文档本质上是纯文本文档,因此可以使用readLines()等函数将其读入R。现在假设你有一个RTF表。要将它嵌入R标记,您需要读取它并传递给knitr::raw_output(),例如,

knitr::raw_output(readLines('table.rtf'))

3.6.1 其它特点

RTF文档的大部分特性的文档请参阅3.1节,包括目录(3.1.1节)图选项(3.1.5节)保留标记(3.1.10.1节)标记扩展(3.1.10.4节)Pandoc参数(3.1.10.5节)共享选项(3.1.11节)

3.7 Markdown文档

要从RMarkdown创建一个Markdown文档,您需要在文档的前面指定md_document输出格式:

---
title: "Habits"
author: John Doe
date: March 22, 2005
output: md_document
---

3.7.1 Markdown变体

默认情况下,md_document格式生成“严格的”标记(即,符合最初的Markdown规范,没有扩展)。您可以使用变体选项生成不同风格的Markdown。例如:

md_document: variant: markdown_github

Valid values are:

  • markdown (Full Pandoc Markdown)

  • markdown_strict (Original Markdown specification; the default)

  • markdown_github (GitHub Flavored Markdown)

  • markdown_mmd (MultiMarkdown)

  • markdown_phpextra (PHP Markdownextra)

您还可以编写自定义标记变体。例如:

output:
  md_document:
    variant: markdown_strict+backtick_code_blocks+autolink_bare_uris

3.7.1.1 出版格式

在许多情况下,您可以简单地将rmarkdown::render()生成的Markdown复制并粘贴到目标系统的编辑接口中。但是,请注意,如果您有嵌入图像,则需要分别载上它们,并修复它们的url以指向上载的位置。如果您打算构建基于RMarkdown的网站,我们建议您使用更直接的解决方案,如blogdown(Xie、Hill和Thomas2017;如第10节所介绍的,而不是手动复制标记内容。

3.7.2 其它特点

有关Markdown文档的其他特性的文档,请参阅3.1节。 包括目录(第3.1.1节)图选项(第3.1.5节)标题和正文包含前后(第3.1.10.2节)Pandoc参数(第3.1.10.5节)共享选项(第3.1.11节)

3.8 R package vignette

html_vignette格式提供了html_document的轻量级替代方案,适合包含在要发布到CRAN的包中。它将基本图形的大小从600Kb减小到10Kb左右。格式不同于传统的HTML文件如下:

要使用html_vignette,您可以将其指定为输出格式,并通过\ vignette *{}宏添加一些额外的vignette相关设置:

---
title: "Your Vignette Title"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteIndexEntry{Your Vignette Title}
  %\VignetteEncoding{UTF-8}
---

如果您想要更大的图形大小,可以在文档输出选项中更改fig_widthfig_height,或者在每个块的基础上覆盖默认选项。


  1. This is a footnote.