節選自 Pimp my RMD: a few tips for R Markdown https://holtzy.github.io/Pimp-my-rmd
章節自動編號在 YAML 文件中用 number_sections: TRUE 參數設置自動編號:
---title: "Your title"output: html_document: number_sections: TRUE---
# Title## A subtitle## Another subtitle
# Another title跳過一行可以用 html 中的 <br> 標籤來插入換行符。
A first sentence<br><br><br><br>A seconde sentence圖片居中
同樣可以用 html 代碼居中圖片
<center></center>減少圖片周圍的空白區域有時候 R 代碼生成的圖片周圍有太多空白,這時可以用 fig.asp 參數來調整。這裡我使用了 fig.asp=0.50。
library(png)library(grid)img <- readPNG("kan.png")grid.raster(img)上圖為未加參數,下圖為添加了參數
添加 footer 和 header我們也可以在文檔的開頭或結尾添加一些 html 代碼。下面是我在本文末尾添加的 html 代碼:
<hr /><p style="text-align: center;">A work by <a href="https://github.com/holtzy/">Yan Holtz</a></p><p style="text-align: center;"><span style="color: #808080;"><em>Yan.holtz.data@gmail.com</em></span></p>
<!-- Add icon library --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Add font awesome icons --><p style="text-align: center;"> <a href="https://twitter.com/r_graph_gallery?lang=en" class="fa fa-twitter"></a> <a href="https://www.linkedin.com/in/yan-holtz-2477534a/" class="fa fa-linkedin"></a> <a href="https://github.com/holtzy/" class="fa fa-github"></a></p>
將這段 html 代碼保存為 footer.html,然後在 YAML 中聲明:
---title: "Your title"output: html_document: includes: after_body: footer.html---你的 footer 就會變成這樣:
在標題前加上空行
除了在每個標題前加上 <br> 外,更方便的辦法是直接在 .css 文件中添加樣式。創建一個 style.css 文件:
h1, .h1, h2, .h2, h3, .h3 { margin-top: 84px;}在 YAML 中指定該 .css:
---title: "A document with a CSS included"output: html_document: css: style.css---
A title will follow, but with a lot of space before it
# Title 1
content of part 1
# Title 2
content of part 2圖注我們可以在代碼塊的 header 中添加圖注,例如:
{r, fig.align="center", fig.width=6, fig.height=6, fig.cap="Figure: Here is a really important caption."}library(tidyverse)mpg %>% ggplot( aes(x=reorder(class, hwy), y=hwy, fill=class)) + geom_boxplot() + xlab("class") + theme(legend.position="none")自定義圖注樣式
同樣可以用 css 自定義圖注樣式,比如把下面的代碼添加到 style.css 文件中:
<style>p.caption { font-size: 0.9em; font-style: italic; color: grey; margin-right: 10%; margin-left: 10%; text-align: justify;}</style>圖注的樣式就會改為這樣:
數學公式
在 R Markdown 中可以用 LaTeX 語法插入數學公式,用 $ 分隔 Latex 語法:
$A = (\pi * \lambda \times r^{4}) / \alpha $並排放兩張圖在 chunk header 中加上 out.width=c('50%', '50%'), fig.show='hold' 即可:
```{r out.width=c('50%', '50%'), fig.show='hold'}boxplot(1:10)plot(rnorm(10))\```為子標題實現選項卡切換的效果
這個樣式同樣用 .css 來實現。
首先,在一級標題後加上 {.tabset .tabset-fade .tabset-pills}(把二級標題作為選項卡)
# Use buttons or tabs for sub-chapters {.tabset .tabset-fade .tabset-pills}***Save space in your document using buttons or tabs for sub chapters. Add this code at the end of your title:
## FirstA first section
## Secondcontent of sub-chapter #2
## Thirdcontent of sub-chapter #3修改 .css:
.btn { border-width: 0 0px 0px 0px; font-weight: normal; text-transform: ;}.btn-default { color: #2ecc71; background-color: #ffffff; border-color: #ffffff;}用 DT 包來展示表格DT 包[1] 可謂是 R Markdown 的最佳伴侶,它可以在網頁上輕鬆實現交互式的表格:
library(DT)datatable(mtcars, rownames = FALSE, filter="top", options = list(pageLength = 5, scrollX=T) )隱藏代碼
有時候你只想分享實驗結果而非一些冗長的代碼,這時就可以在 YAML 中設置參數來隱藏代碼:
output: html_document: code_folding: "hide"高亮一段話同樣,我們可以用 css 代碼來改變段落的背景色以高亮顯示:
<style>div.blue { background-color:#e6f0ff; border-radius: 5px; padding: 20px;}</style><div class = "blue">
- This is my first conclusion- This is my second conclusion
</div>視差滾動
因為 R Markdown可以輸出 html 文檔,所以理論上可以實現網頁中的各種視覺效果。比如實現「視差滾動」:
需要用到的 css 和 header.html 可從這裡下載:https://github.com/holtzy/R-Markdown-Parallax
緩存可以在代碼塊的 header 中添加 cache=TRUE 來緩存特定 chunk,也可以直接在文檔的最開始加上 knitr::opts_chunk$set(cache=TRUE) 實現對整個文檔的緩存。
注意:請謹慎使用此選項,強烈建議閱讀 Yiyi Xie 撰寫的有關此部分內容的文檔[2]。
在網頁右上角加上 Github 連結為了實現這種效果,我一般用的是 Tim Holman 的代碼[3],把這段代碼粘貼到 header.html 中,使用方法同添加 footer 代碼一樣。
內部連結
您可以使用錨點在 R Markdown 中使用內部連結(可通過錨點連接網頁內的任意標題)。如何實現這個效果:
•第一步 - 在標題處添加一個錨點:
# Add a github link in the corner of your document {#github-link}•第二步 - 用連結指向該錨點:
For example, [this link](#github-link) will bring ...交互式圖表可使用 plotly 構建交互式圖表,充分利用 html 可交互的特性。
library(ggplot2)library(plotly)library(gapminder)
p <- gapminder %>% filter(year==1977) %>% ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) + geom_point() + scale_x_log10() + theme_bw()
ggplotly(p)主題
你可以使用任何 bootswatch 主題[4]來自定義文檔的字體和外觀。還可以調整高亮顯示樣式:
title: "your title"output: html_document: theme: sandstone highlight: tango模板R Markdown 可以使用許多美觀的模板,這裡推薦兩個包:
•prettydoc[5] by Yixuan Qiu•rmdformats[6] by Julien Barnier. It provides several templates, like readthedown:
把網頁分享到網際網路上
按照下面的步驟就可以把你的 html 放在 github 上顯示啦:
1.創建 github 帳號。2.將 .rmd 文件重命名為 index.rmd,並 Knit 生成 index.html 文件。3.使用工作目錄生成一個 github 倉庫4.進入該倉庫:Settings -> GitHub Pages -> Source -> Master Branch -> Save5.稍等一會你的 .html 文件就可在相應域名訪問。
用 R Markdown 創建靜態網頁這一部分內容可參見 blogdown package[7] 。
創建 R Markdown 模板關於這個話題詳細內容參見 Rstudio documentation[8] 。
Session info在文檔末尾添加 session info 是一個比較好的習慣,這將提高結果的可重複性。只需一行代碼即可實現:
## R version 3.4.1 (2017-06-30)## Platform: x86_64-apple-darwin15.6.0 (64-bit)## Running under: macOS Sierra 10.12.6## ## Matrix products: default## BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib## LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib## ## locale:## [1] en_AU.UTF-8/en_AU.UTF-8/en_AU.UTF-8/C/en_AU.UTF-8/en_AU.UTF-8## ## attached base packages:## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages:## [1] bindrcpp_0.2.2 gapminder_0.3.0 plotly_4.7.1 DT_0.4 ## [5] forcats_0.3.0 stringr_1.3.1 dplyr_0.7.8 purrr_0.2.5 ## [9] readr_1.1.1 tidyr_0.8.2 tibble_1.4.2 ggplot2_3.1.0 ## [13] tidyverse_1.2.1 rmarkdown_1.9 epuRate_0.1 ## ## loaded via a namespace (and not attached):## [1] Rcpp_1.0.0 lubridate_1.7.4 lattice_0.20-35 ## [4] assertthat_0.2.0 rprojroot_1.3-2 digest_0.6.18 ## [7] psych_1.8.3.3 mime_0.5 R6_2.3.0 ## [10] cellranger_1.1.0 plyr_1.8.4 backports_1.1.2 ## [13] evaluate_0.10.1 httr_1.3.1 highr_0.6 ## [16] pillar_1.2.2 rlang_0.3.0.1 lazyeval_0.2.1 ## [19] readxl_1.1.0 rstudioapi_0.7 data.table_1.11.4## [22] labeling_0.3 foreign_0.8-70 htmlwidgets_1.2.1## [25] munsell_0.5.0 shiny_1.1.0 broom_0.4.4 ## [28] compiler_3.4.1 httpuv_1.4.3 modelr_0.1.1 ## [31] pkgconfig_2.0.2 mnormt_1.5-5 htmltools_0.3.6 ## [34] tidyselect_0.2.5 viridisLite_0.3.0 crayon_1.3.4 ## [37] withr_2.1.2.9000 later_0.7.2 grid_3.4.1 ## [40] nlme_3.1-137 jsonlite_1.5 xtable_1.8-2 ## [43] gtable_0.2.0 magrittr_1.5 scales_1.0.0.9000## [46] cli_1.0.0 stringi_1.2.4 reshape2_1.4.3 ## [49] promises_1.0.1 xml2_1.2.0 tools_3.4.1 ## [52] glue_1.3.0 hms_0.4.2 crosstalk_1.0.0 ## [55] parallel_3.4.1 yaml_2.1.19 colorspace_1.3-2 ## [58] rvest_0.3.2 knitr_1.20 bindr_0.1.1 ## [61] haven_1.1.1一些快捷鍵運行代碼command + Enter on MacCtrl + Enter on Windows插入注釋command + Shift + C on MacCtrl + Shift + C on WindowsKnit a R Markdown documentcommand + Shift + K on MacCtrl + Shift + K on Windows創建新的代碼塊command + option + I on Mac (or command + alt + I depending on your keyboard)Ctrl + ALT + I on Windows重新格式化代碼cmd + Shift + A on MacCtrl + Shift + A on Windows引用連結[1] DT 包: https://rstudio.github.io/DT/
[2] Yiyi Xie 撰寫的有關此部分內容的文檔: https://yihui.name/knitr/demo/cache/
[3] Tim Holman 的代碼: https://github.com/tholman/github-corners
[4] bootswatch 主題: https://bootswatch.com/
[5] prettydoc: http://yixuan.cos.name/prettydoc/
[6] rmdformats: https://github.com/juba/rmdformats
[7] blogdown package: https://github.com/rstudio/blogdown
[8] Rstudio documentation: https://rmarkdown.rstudio.com/developer_document_templates.html生信技能樹目前已經公開了三個生信知識庫,記得來關注哦~
每周文獻分享
https://www.yuque.com/biotrainee/weeklypaper
腫瘤外顯子分析指南
https://www.yuque.com/biotrainee/wes
生物統計從理論到實踐
https://www.yuque.com/biotrainee/biostat
友情宣傳強烈建議你推薦給身邊的博士後以及年輕生物學PI,多一點數據認知,讓他們的科研上一個臺階:
•生信技能樹的2019年終總結,你的生物信息學成長寶藏•2020學習主旋律,B站74小時免費教學視頻為你領路•全國巡講全球聽(買一得五),你的生物信息學入門課