Rmarkdown Basics
2023-03-22
1 Installation
- 安装 R
- 安装 Rstudio
- 加载
rmarkdown package
# 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 TinyTeX3 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提供了漂亮的格式
rmdformatsprettydocrticlestuftecerulean
- 安装好上述包后,可以通过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
R package:bookdown拓展了Rmarkdown的功能,提供了诸如gitbook等格式
5 R Markdown syntax
5.1 参考资料
- 采用 pandoc’s markdown语法
- R markdown cheatsheet
- 在Rstudio里打开快速指南
R studio-help-markdown quick reference
5.2 常用语法
5.2.1 字体
- 斜体:
*text*或_text_ - 粗体:
**text**或__text__ - 上标:
^supersript^ - 下标:
~subscript~ 删除线:~~strikethrough~~
5.2.2 链接
---
title: "Rmarkdown Basics"
author: "lmj"
date: "2023-03-22"
output:
bookdown::html_document2:
base_format: gitbook
bibliography: Liu.bib
---- 然后通过
@citation label或[@citation label]引用,例如:
This is my first ES&T paper (Liu et al. 2023)
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.
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是否展示源代码resultshide不展示结果hold所有结果一起展示在该段代码最下端asis安装markdown的语法输出,如下面的Markdown显示为Markdown而不是**Markdown**
cat('**Markdown** is cool.\n')Markdown is cool.
collapse是否将代码和结果合并在一起输出,设置为TRUE可以使结构更紧凑warningmessageerror是否显示代码的警告、信息和错误。注意,如果设置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.dimc(6,4)表示宽6高4fig.asp宽度/高度out.widthandout.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.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")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)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))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.'
)| 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
)
|
|
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
8 interactive documents
8.1 HTML widgets
- htmlwidgets将javascript库导入R
- 基于其发展了一些R packages
- DT
- leaflet
- dygraphs
- 更多关于htmlwidgets for R
#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绘图可以通过将其包装在
Shiny的renderPlot()函数中进行交互。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")- 更多关于shiny
References & footnotes
This is a footnote.↩︎