1 Installation

# Install from CRAN
install.packages('rmarkdown')

# Or if you want to test the development version,
# install from GitHub
if (!requireNamespace("devtools"))
  install.packages('devtools')
devtools::install_github('rstudio/rmarkdown')
  • 如果需要输出PDF格式,需要下载TinyTex
install.packages('tinytex')
tinytex::install_tinytex()  # install TinyTeX

3 Compile R markdown document

  • 使用Rstudio的knit 按钮
  • 使用快捷键 ctrl+shift+k
  • 使用函数 rmarkdown::render
rmarkdown::render('basic.Rmd', 'html_document')
  • 另一个函数xaringan::inf_mr 使你可以在保存时,通过Rstudio的Viewer窗口实时预览输出,不需要按下Knit按钮

4 Output format

  • 通过YAML metadata里的output设置,例如,本文档的YAML头文件
---
title: "Rmarkdown Basics"
author: "lmj"
date: "2023-03-22"
output: 
  bookdown::html_document2: 
    base_format: gitbook
bibliography: Liu.bib
---
  • 许多R package提供了漂亮的格式
    • rmdformats
    • prettydoc
    • rticles
    • tufte
    • cerulean
  • 安装好上述包后,可以通过Rstudio调用:File-New file-R markdown-From template使用模板
  • 或者添加格式到YAML头文件里使用
output: tufte::tufte_html
  • 也可以自定义output参数:查看格式参数 ?rmarkdown::html_document
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'
  • YAML中需要解析的内容前面加 !exr
 output:
  html_document:
    theme: !expr sample(c("yeti", "united", "lumen"), 1)
#随机选一个theme

5 R Markdown syntax

5.1 参考资料

5.2 常用语法

5.2.1 字体

  • 斜体: *text*_text_
  • 粗体**text**__text__
  • 上标: ^supersript^
  • 下标~subscript~
  • 删除线~~strikethrough~~

5.2.3 分区元素

  • 节标题
# First-level header
## Second-level header
### Third-level header
  • 非排序列表 - + * 引导
- one item
- one item
- one item
  - one more item
  - one more item
  - one more item
  • 排序列表 1. 2. 数字引导
1. the first item
2. the second item
3. the third item
  - one unordered item
  - one unordered item
  • 纯代码块 ```text```
This text is displayed verbatim / preformatted
  • 引用块 >text

“To be or not to be, that is a question.

—ShakeSpear

  • 注意不同元素之间需要空行防止模糊识别, 例如下面两个例子中的#-没有被识别为分区元素
    • In R, the character # indicates a comment.

    • The result of 5 -3 is 2.

5.2.4 数学表达式

  • 采用latex数学表达式
  • in-line 表达式:$equation$ \(f(k) = {n \choose k} p^{k} (1-p)^{n-k}\)
  • 独段表达式:$$equation$$ \[f(k) = {n \choose k} p^{k} (1-p)^{n-k}\]

6 R chunks

6.1 插入R code

  • 快捷键 Ctrl + Alt + I
  • Rstudio button +C
  • markdown 语法
    • 代码条: `This is a in-line code`
    • 代码块: ```code```
      ```{r, chunk-label, results='hide', fig.height=4}```

6.2 Chunk options

  • eval 是否运行代码块
  • echo 是否展示源代码
  • results
    • hide 不展示结果
    • hold 所有结果一起展示在该段代码最下端
    • asis 安装markdown的语法输出,如下面的Markdown显示为Markdown而不是**Markdown**
cat('**Markdown** is cool.\n')

Markdown is cool.

  • collapse 是否将代码和结果合并在一起输出,设置为TRUE可以使结构更紧凑

  • warning message error是否显示代码的警告、信息和错误。注意,如果设置error = FALSE, rmarkdown::render()将在代码块中的错误时暂停,并且错误将显示在R控制台中。

  • include 是否展示code的所有信息,包括代码、输出结果、报错、警告等

    • 如果include=F但是eval=T,仍会运行代码,但所有相关内容都不展示
    • 如果要设置echo = FALSE, results = 'hide', warning = FALSE, message = FALSE,那么可以直接通过设置include=F一次性完成
  • cache 是否保存记录,如果设置为T,那么下次重复knit的时候将直接使用上一次的结果,避免重复运行

  • 设置图片输出格式

    • fig.width 宽度
    • fig.height 高度
    • fig.dim c(6,4)表示宽6高4
    • fig.asp 宽度/高度
    • out.width and out.height 图片输出占页面的比例
    • fig.align 图片排布位置,可选'left', 'center', or 'right'
    • fig.cap 图名
    • dev 图片格式,可选'pdf','png','svg','jpeg'
  • child 可以在主文档中包含子文档。此选项获取一个外部文件的路径。

  • Chunk label是一个可选的chunk选项。如果缺少,将生成一个默认形式为unnamed-chunk-i的标签,其中i是逐个递增的。在label中最好只使用字母数字字符(a-z, a-z和0-9)和破折号(-),因为它们不是特殊字符,肯定适用于所有输出格式。

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

  • 更多详细信息

6.3 Figures

6.3.1 使用markdown 插入图片

![alt text or image title](path/to/image),例如:

中国科学院大学

6.3.2 使用R code插入图片

  • chunk option中设置图片格式(Section 6.2)
fig.cap='A figure example with a relative width 50%.',
fig.width =6,fig.asp=0.7,
fig.align='center',out.width='50%'
par(mar = c(4, 4, 0.1, 0.1))
plot(pressure, pch = 19, type = "b")
A figure example with a relative width 50%.

Figure 6.1: A figure example with a relative width 50%.

  • 设置fig.show='hold',out.width='40%' 将两张图片并排显示
par(mar = c(4, 4, 0.1, 0.1))
plot(pressure, pch = 19, type = "b")
plot(cars, pch = 19)
Two plots placed side by side.Two plots placed side by side.

Figure 6.2: Two plots placed side by side.

  • 使用knitr::include_graphics插入图片,相比于使用markdown语法,具有以下优点
    • 各种格式均适用(Rmarkdown,LaTeX)
    • 可以采用fig.设置大小尺寸名称
knitr::include_graphics(rep("https://www.ucas.ac.cn/newStyle/images/lougou.png", 3))
UCAS LogoUCAS LogoUCAS Logo

Figure 6.3: UCAS Logo

6.4 Tables

6.4.1 使用R code插入表格

  • knitr::kable导出R code表格,其中用参数caption指定表格名
knitr::kable(
  head(mtcars[, 1:8], 10), booktabs = TRUE,
  caption = 'A table of the first 10 rows of the mtcars data.'
)
Table 6.1: A table of the first 10 rows of the mtcars data.
mpg cyl disp hp drat wt qsec vs
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1
  • 将多个表格包装进一个list同时导出
knitr::kable(
  list(
    head(iris[, 1:2], 3),
    head(mtcars[, 1:3], 5)
  ),
  caption = 'A Tale of Two Tables.', booktabs = TRUE
)
Table 6.2: A Tale of Two Tables.
Sepal.Length Sepal.Width
5.1 3.5
4.9 3.0
4.7 3.2
mpg cyl disp
Mazda RX4 21.0 6 160
Mazda RX4 Wag 21.0 6 160
Datsun 710 22.8 4 108
Hornet 4 Drive 21.4 6 258
Hornet Sportabout 18.7 8 360

6.4.2 使用Pandoc语法

  • pandoc 支持多种表格格式
    • simple tables
    • multiline tables
    • grid tables
    • pipe tables
      • 开始和结束管道字符|是可选的,但所有列之间都需要管道。
      • 冒号表示列对齐。
      • 标题不能省略。若要模拟无表头的表,请包含带有空白单元格的表头。
#有表头的pipe table
| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
|   12  |  12  |    12   |    12  |
|  123  |  123 |   123   |   123  |
|    1  |    1 |     1   |     1  |
Right Left Default Center
12 12 12 12
123 123 123 123
1 1 1 1
#无表头的pipe table
|       |      |         |        |
|------:|:-----|---------|:------:|
|   12  |  12  |    12   |    12  |
|  123  |  123 |   123   |   123  |
|    1  |    1 |     1   |     1  |
12 12 12 12
123 123 123 123
1 1 1 1

7 Cross-reference

7.1 采用超链接形式

7.2 采用bookdown拓展的交叉引用方式

  • 基本的格式为 \@ref(label),图片,表格,label前需要加前缀 fig:,tab:
  • 引用节 在节后面通过{#label}设置label Section 4
  • 引用图片时label为R code的label Figure 6.1
  • 引用表格时label为R code的label Table 6.1

8 interactive documents

8.1 HTML widgets

#install.packages('DT')
DT::datatable(iris)
  • 当输出非html文件时,HTML小部件将自动通过webshot包呈现为截取的屏幕截图
install.packages("htmlwidgets")
install.packages("webshot")
webshot::install_phantomjs()

8.2 Web pages

  • knitr::include_url()导入网页
knitr::include_url('https://bookdown.org/yihui/bookdown/web-pages-and-shiny-apps.html',height = '600px')

8.3 Shiny apps

  • 要从R Markdown文档中调用Shiny代码,请将runtime: Shiny添加到YAML元数据中
---
title: "A Shiny Document"
output: html_document
runtime: shiny
---
  • 标准的R绘图可以通过将其包装在ShinyrenderPlot()函数中进行交互。selectInput()函数创建了驱动图形的输入小部件。
#install.packages('shiny')
selectInput(
  'breaks', label = 'Number of bins:',
  choices = c(10, 20, 35, 50), selected = 20
)

renderPlot({
  par(mar = c(4, 4, .1, .5))
  hist(
    faithful$eruptions, as.numeric(input$breaks),
    col = 'gray', border = 'white',
    xlab = 'Duration (minutes)', main = ''
  )
})
  • knitr::include_app()可以导入Shiny apps
#knitr::include_app("https://psim.shinyapps.io/business_game/",height = "600px")

References & footnotes

Liu, Mengjie, Nigel J. D. Graham, Lei Xu, Kai Zhang, and Wenzheng Yu. 2023. “Bubbleless Air Shapes Biofilms and Facilitates Natural Organic Matter Transformation in Biological Activated Carbon.” Environmental Science & Technology 57 (11): 4543–55. https://doi.org/10.1021/acs.est.2c08889.

  1. This is a footnote.↩︎