R 包 | R Markdown:數據報告生成利器#
R Markdown 站在 knitr 和 Pandoc 的肩膀上,前者執行嵌入於文檔中的計算機代碼,並將 R Markdown 轉換為 Markdown;後者將 Markdown 呈現出您想要的輸出格式(如 PDF、HTML、Word 等)此篇文章翻譯自謝益輝新書 《R Markdown: The Definitive Guide》 的前三章節,內容有所刪減,主要介紹了 R Markdown 的相關結構及語法規則,如果想了解更多更詳細的內容推薦您閱讀原書。
安裝#
這裡假設您已經安裝了 R (https://www.r-project.org) 和 RStudio IDE (https://www.rstudio.com) 。Rstudio 並不是必須的,但安裝它會使您更加容易地使用 R Markdown。如果您沒有安裝 RStudio IDE,您將不得不安裝 Pandoc( http://pandoc.org ),否則就不需要單獨安裝 Pandoc,因為在安裝 RStudio 時已經將它捆綁安裝了。接下來,您可以在 R 中安裝 rmarkdown
包:
# 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 類型文檔輸出,您將需要安裝 LaTeX 。對於那些以前沒有安裝過 LaTeX 的 R Markdown 用戶,我們建議您安裝 TinyTeX(https://yihui./tinytex/):
install.packages("tinytex")
tinytex::install_tinytex() # install TinyTeX
TinyTeX 相當於一款輕量級、跨平台、易於維護的 LaTeX 。在將 LaTeX 或 R Markdown 文檔編譯成 PDF 時,tinytex
可以幫助您自動安裝所需的相關 R 包,同時還能確保一個 LaTeX 文檔被編譯成正確的次數,以解決所有的交叉引用問題。如果您不明白這兩件事是什麼意思,應該按照我們的建議來安裝 TinyTeX,因為這些細節往往並不值得您花費時間和精力去關心。
使用 rmarkdown
包、RStudio/Pandoc 和 LaTeX,您應該能夠編譯大多數 R Markdown 文檔。在某些情況下,您可能需要其他軟件包,我們將在必要時提到它們。
參考文獻
- R Core Team. 2018. R: A Language and Environment for Statistical Computing. Vienna, Austria: R Foundation for Statistical Computing. https://www.R-project.org/.
- Xie, Yihui. 2018f. Tinytex: Helper Functions to Install and Maintain Tex Live, and Compile Latex Documents. https://github.com/yihui/tinytex.
基礎知識#
R Markdown 為數據科學提供了一個創作框架。R Markdown 能勝任以下兩個任務:
- 保存並執行代碼;
- 生成可共享的高質量報告。
R Markdown 的設計初衷是為了更容易地實現報告內容的可重複性,這是因為計算代碼和敘述都在同一個文檔中,結果是由源代碼自動生成的。並且 R Markdown 支持數十種靜態和動態 / 互動式輸出格式。
如果您更喜歡觀看視頻進行學習,我們建議您查看網站 https://rmarkdown.rstudio.com,並在 “Get Started” 中觀看視頻,其中包括了 R Markdown 的基礎知識。
文檔結構#
下面是一份非常簡易的 R Markdown 文檔,是一個帶有 .Rmd
拓展名的純文本文檔。
---
title: "Hello R Markdown"
author: "Awesome Me"
date: "2018-02-14"
output: html_document
---
This is a paragraph in an R Markdown document.
Below is a code chunk:
```{r}
fit = lm(dist ~ speed, data = cars)
b = coef(fit)
plot(cars)
abline(fit)
```
The slope of the regression is `r b[1]`.
```
```
您可以使用任何文本編輯器(包括但不限於 RStudio)來創建這樣的文本文檔。如果使用 RStudio,您可以從 File -> New File -> R Markdown
中創建一個新的 Rmd 文檔。
一份 R Markdown 文檔有三個基礎組成部分:元數據,文本和代碼。元數據是在三個連接符 ---
之間的內容。元數據的語法是 YAML( YAML 不是標記語言 ),所以有時它也被稱為 YAML metadata 或 YAML frontmatter。 需要注意的是,縮進在 YAML 中十分重要,忽視它會讓你付出慘重代價。請參閱謝益輝所寫的 《bookdown》(2016)一書中的 附錄 b.2 來了解一些簡單的例子,這些示例展示了 YAML 語法。
文檔的主體遵循元數據書寫的規則。文本的語法是 Markdown,將在第 2.5 節中進行介紹。有兩種類型的計算機代碼,在第 2.6 節中進行了詳細解釋:
- 代碼塊:以三個重音符及所使用語言開始,其中
r
代表所使用的程序語言,並以三個重音符結束。 可以在花括號中填寫塊選項(如:將圖形高度設置為 5 英寸:{r, fig.height=5}
)。 - 內聯代碼:以 ``r` 開始,並以單個重音符結束。
文檔編譯#
最簡單的方式莫過於在 RStudio 中單擊 Knit
按鈕,對應的快捷鍵為 Ctrl + Shift + K
(在 macOS 中為 Cmd + Shift + K
)。當然也可以直接運行代碼 rmarkdown::render
來進行渲染編譯,如:
rmarkdown::render('foo.Rmd', 'pdf_document')
當編譯多個文檔時,使用函數更加方便,因為可以直接使用循環來進行渲染編譯。
參考卡片#
RStudio 已經創建了大量的參考卡片,它們可以在 https://www.rstudio.com/resources/cheatsheets/ 上免費獲得。
輸出格式#
有兩種輸出格式:documents 和 presentations 。所有可用的格式如下所示 :
beamer_presentation
github_document
html_document
ioslides_presentation
latex_document
md_document
odt_document
pdf_document
powerpoint_presentation
rtf_document
slidy_presentation
word_document
我們將在第 3 章和第 4 章詳細地記錄這些輸出格式。在其他擴展包中提供了更多的輸出格式(從第 5 章開始)。對於 Rmd 文件的 YAML 元數據中的輸出格式名稱,如果格式來自擴展包,您需要包含包名(若格式來自於 rmarkdown
包,則不需要 rmarkdown::
前綴 ),例如:
output: tufte::tufte_html
每種輸出格式通常都有多種格式選項。所有這些選項都記錄在 R 包 help 頁面上。例如,您可以在 R 中鍵入 ?rmarkdown::
打開關於 html_document
格式的 help 頁面。當您想要使用某些選項時,必須將這些值從 R 轉換成 YAML,例如:
html_document(toc = TRUE, toc_depth = 2, dev = 'svg')
可以用 YAML 寫為:
output:
html_document:
toc: true
toc_depth: 2
dev: "svg"
YAML 中的字符串通常不需要引號(``dev:“svg”和
dev是相同的),除非它們包含特殊字符,比如冒號
:。如果您不確定是否應該引用字符串,那麼用
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 中的列表),則子選項需要進一步縮進,例如:
output:
html_document:
toc: true
includes:
in_header: header.html
before_body: before.html
一些選項將被傳遞給 knitr ,比如 dev
、fig_width
和 fig_height
。這些選項的詳細文檔可以在 knitr 文檔頁面 上找到。請注意,實際的 knitr 選項名稱可能有所不同。特別是,knitr 在名稱中使用 .
,但 rmarkdown 使用 _
,例如,在 rmarkdown 中,fig_width
對應於 knitr 中的 fig.width
。
一些選項將被傳遞給 Pandoc,比如 toc
、toc_depth
和 number_sections
。當有疑問時,您應該參考 Pandoc 文檔。R Markdown 輸出格式函數通常有一個pandoc_args
參數,它應該是傳遞給 Pandoc 的參數的字符向量。如果您發現任何沒有由輸出格式參數表示的 Pandoc 特性,您可以使用這個終極論證,例如:
output:
pdf_document:
toc: true
pandoc_args: ["--wrap=none", "--top-level-division=chapter"]
Markdown 語法#
內聯格式#
-
斜體 :
_text_
或*text*
-
粗體 :
**text**
-
下標 :
H~3~PO~4~
渲染為 $H_3PO_4$ -
上標 :
Cu^2+^
渲染為 $Cu^{2+}$ -
腳註 :
^[This is a footnote.]
-
內聯代碼 :
`code`
, 可以使用 n+1 個重音符輸出包含 n 個重音符的代碼塊。 -
超鏈接 :
[text](link)
-
圖片鏈接 :

-
引用 :
@Manual{R-base, title = {R: A Language and Environment for Statistical Computing}, author = {{R Core Team}}, organization = {R Foundation for Statistical Computing}, address = {Vienna, Austria}, year = {2017}, url = {https://www.R-project.org/}, }
塊級元素#
-
標題
# First-level header ## Second-level header ### Third-level header
如果不想讓某個標題被編號,可以在標題後面添加
{-}
或者{.unnumbered}
,如:# Preface {-}
-
無序列表
- 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
-
代碼塊
``` This text is displayed verbatim / preformatted ``` Or indent by four spaces: This text is displayed verbatim / preformatted
數學表達式#
$f(k) = {n \choose k} p^{k} (1-p)^{n-k}$
: $f(k) = {n \choose k} p^{k} (1-p)^{n-k}$
$$f(k) = {n \choose k} p^{k} (1-p)^{n-k}$$
:
代碼塊選項#
單擊 Insert
按鈕,對應快捷鍵為 Ctrl + Alt + I
(macOS:Cmd + Option + I
)。
在 https://yihui.name/knitr/options 中有大量的代碼塊可選項,在此我們列出常用的一部分:
-
eval=TRUE
:執行當前代碼塊;```{r} # execute code if the date is later than a specified day do_it = Sys.Date() > '2018-02-14' ``` ```{r, eval=do_it} x = rnorm(100) ```
-
echo=TRUE
:輸出源代碼; -
result
:當設置為'hide'
,文本輸出將被隱藏;當設置為'asis'
,文本輸出將被 “原樣” 书写。 -
collapse=TRUE
:將文本輸出和源代碼合併為單個代碼塊輸出,更加緊湊; -
warning
,message
,error
:是否在輸出文檔中顯示警告、消息和錯誤; -
include=FALSE
:運行當前代碼並且不顯示任何源代碼與輸出結果; -
cache
:是否啟用高速緩存。如果啟用了緩存,則在下一次編譯文檔時不會對相同的代碼塊進行評估(如果代碼塊沒有被修改),這將節省您的時間; -
fig.width
,fig.height
:(圖形設備)塊的大小(英寸)。注意:fig.dim = c(6, 4)
意味著fig.width = 6
並且fig.height = 4
; -
out.width
,out.height
:輸出文檔中 R 圖片的輸出大小。可以使用百分比,例如out.width = '80%'
表示頁面寬度的 80%; -
fig.align
:圖片的對齊方式; -
dev
:圖形設備保存 R 圖片的格式。如'pdf'
,'png'
,'svg'
,'jpeg'
; -
fig.cap
:圖片標題; -
child
:您可以在主文檔中包含子文檔。這個選項選擇一條通向外部文件的路徑。
如果某個選項需要經常被設置為多個代碼塊中的值,您可以考慮在文檔的第一個代碼塊中全局設置它:
```{r, setup, include=FALSE}
knitr::opts_chunk$set(fig.width = 8, collapse = TRUE)
```
圖片#
本地圖片亦可以使用代碼塊選項進行調節,例如:
```{r, out.width='25%', fig.align='center', fig.cap='...'}
knitr::include_graphics('images/hex-rmarkdown.png')
```
如果您想要淡入一個不是由 R 代碼生成的圖形,您可以使用 knitr::include_graphics()
函數,它使您能夠更好地控制圖像的屬性,而不是像 
這樣的 Markdown 語法難以調解圖片屬性。
表格#
使用 knitr::kable()
函數可以簡易的創建表格,表格標題可以通過 caption
來設置,例如:
```{r tables-mtcars}
knitr::kable(iris[1:5, ], caption = 'A caption')
```
如果您正在尋找更高級的表格樣式控制,建議您使用 kableExtra 包,它提供了定制 PDF 和 HTML 表格外觀的功能。在第 12.3 節中解釋了 bookdown
包如何擴展 rmarkdown 的功能,以允許在文本中輕鬆地交叉引用數字和表格。
參考文獻
- Xie, Yihui. 2015. Dynamic Documents with R and Knitr. 2nd ed. Boca Raton, Florida: Chapman; Hall/CRC. https://yihui.name/knitr/.
輸出文檔#
HTML 文檔#
為了輸出 HTML 文檔,首先要在 YAML 元數據中寫入 output: html_document
:
---
title: Habits
author: John Doe
date: March 22, 2005
output: html_document
---
目錄(Table of contents)#
---
title: "Habits"
output:
html_document:
toc: true
toc_depth: 2
toc_float:
collapsed: false
smooth_scroll: false
---
toc: true
:輸出目錄;toc_depth
:所輸出標題的最小級別;toc_float: true
:目錄懸停於內容左側,並一直可見;collapsed
(默認為TRUE
) :初始只顯示頂級標題,隨內容滾動目錄逐級展開;smooth_scroll
(默認為TRUE
) :點擊目錄標題是否導航到指定內容。
目錄編號 (Section numbering)#
---
title: "Habits"
output:
html_document:
toc: true
number_sections: true
---
注意,如果文檔中沒有一级標題,那麼二級標題將被命名為 0.1
, 0.2
……
選項卡 (Tabbed sections)#
## Quarterly Results {.tabset .tabset-fade .tabset-pills}
### By Product
(tab content)
### By Region
(tab content)
.tabset
:使主標題的所有子標題與 .tabset 屬性一起出現在選項卡中,而不是作為獨立的部分;.tabset-fade
:選項卡切換時淡入淡出;.tabset-pills
:改變選項卡外觀,使其類似 “藥丸”。
外觀與風格#
---
title: "Habits"
output:
html_document:
theme: united
highlight: tango
---
theme
:主題是從 Bootswatch 主題庫中提取的,適用的主題包括:default
,cerulean
,journal
,flatly
,readable
,spacelab
,united
,cosmo
,lumen
,paper
,sandstone
,simplex
, 和 `yeti.highlight
:代碼高亮模式。支持的風格包括:default
,tango
,pygments
,kate
,monochrome
,espresso
,zenburn
,haddock
和textmate
.
圖片選項#
---
title: "Habits"
output:
html_document:
fig_width: 7
fig_height: 6
fig_caption: true
---
fig_width
和fig_height
:圖片寬度和高度;fig_caption
:控制圖片是否包括標題;dev
:圖片渲染格式,默認為png
。
表格打印#
默認表格輸出格式為:
Option | Description |
---|---|
default | Call the print.data.frame generic method |
kable | Use the knitr::kable function |
tibble | Use the tibble::print.tbl_df function |
paged | Use rmarkdown::print.paged_df to create a pageable table |
設定為 paged 格式後輸出形式為:
---
title: "Motor Trend Car Road Tests"
output:
html_document:
df_print: paged
---
``` {r, rows.print=5}
mtcars
```
TABLE 3.2: The options for paged HTML tables.
Option | Description |
---|---|
max.print | The number of rows to print. |
max.print | The number of rows to print. |
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. |
pages.print | The number of pages to display under page navigation. |
rownames.print | When set to FALSE turns off row names. |
代碼折疊#
---
title: "Habits"
output:
html_document:
code_folding: hide
---
code_folding: hide
:初始默認不顯示代碼,查看者可點擊進行顯示;code_folding: show
:初始默認顯示代碼,查看者可點擊進行隱藏;
高級定制#
保留 Markdown 文件#
當運行一個 R Markdown 文件(*.Rmd
)時,將創造一個 Markdown 文件(*.md
)並將該文件通過 Pandoc 轉換為 HTML 文件。如果想要保留 Markdown 文件,可以使用 keep_md
選項:
---
title: "Habits"
output:
html_document:
keep_md: true
---
添加本地 HTML 文檔#
可以通過添加額外的 HTML 內容或完全替換核心 Pandoc 模板來完成更高級的輸出定制。為了在文檔頭部或文檔主體之前 / 之後包含內容,您可以使用以下選項:
---
title: "Habits"
output:
html_document:
includes:
in_header: header.html
before_body: doc_prefix.html
after_body: doc_suffix.html
---
自定義模板#
---
title: "Habits"
output:
html_document:
template: quarterly_report.html
---
有關模板的其他詳細信息,請參考 Pandoc 模板 上的文檔。您還可以研究默認的 HTML 模板 default.html5
。
其他類型文檔格式控制方式類似,如欲詳細了解請 參考原作 。