關於 R Markdown 的一些 tips

2021-02-20 生信菜鳥團

節選自 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>![FigName](logo_r_graph_gallery.jpg)</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 Windows

Knit a R Markdown document
command + 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小時免費教學視頻為你領路•全國巡講全球聽(買一得五),你的生物信息學入門課

相關焦點

  • R Markdown 簡介
    R Markdown文檔編輯需要 rmarkdown包,rmarkdown安裝需要RStudio編輯器環境,但是你可以以github途徑來下載rmarkdown,並安裝。knit - knit 文件. rmarkdown包調用knitr包, knitr 將運行所有的R代碼,並將得到的結果追加到代碼之後,這種工作方式非常節省實踐並且報告也可復用。傳統的,作者製作包含圖形的報告。
  • 從rmarkdown到PDF
  • 「R」Rmarkdown與Shiny
    RmarkdownRmarkdown擴展了markdown的語法,所以markdown能寫的,Rmarkdown能寫,後者還提供了一些新的特性,特別是圖表,很nice。markdown的語法非常非常簡單,用上一天就熟悉了,還沒學過的隨便百度谷歌下,教程已經爛大街了,如果你實在要我推薦,就看看我之前寫的【軟體推薦|markdown】Typora簡介及Markdown語法精講[1]吧。
  • R Markdown 詳細使用指南(一)
    因此仍然需要闡述清楚一些必要的參數:```{r setup, include=FALSE}knitr::opts_chunk$set(echo = TRUE,        tidy = F,        highlight = T,        prompt = F,
  • 如何用R-Markdown製作名片
    上一篇介紹了如何用R-Markdown寫正式的書信,同樣是pagedown這個包,其中包含如何用R-markdown來做名片,信件,期刊論文,學位論文
  • markdown常用語法
    markdown寫筆記很方便,語法也很簡潔。
  • 基於 R Markdown 的演示文稿和報告模板使用經驗
    作為排版困難者,我嘗試著探索了一些只關注內容的幻燈片和報告的寫法。隨著四年統計學習,R 雖然已經快脫離我的常用語言名單,但不希望我積累的那些利用 R Markdown 製作幻燈片和課程報告的經驗隨著我的不用而消亡,故記錄下一些改裝模板的經驗。本文適合會 R Markdown、想自定義模板的人閱讀。
  • R Markdown與RStudio IDE深度結合
    RStudio將會打開一個新 .Rmd 文件,文件包含YAML內容,包括所有文件參數,當然你必須用正確的 rmarkdown::render(),你也可以後續手動修改參數。RStudio將創建一個簡單的模板範文,呈現少數基礎的特性,那麼,這就意味這你能立馬執行這個文件,下圖展示了交互式文件的模板。
  • Rmarkdown以及Rstudio安裝配置debug
    install.packages("ggplot2", repos = "http://cran.rstudio.com")如果想root權限來安裝R包,則:sudo su - -c "R -q -e \"install.packages('ggplot2', repos='http://cran.rstudio.com/')\""但有時一些腳本裡以被開發者切入了安裝
  • 如何用R-Markdown製作教學大綱
    首先,我在網上找的一個很好的模板,大家可以自行下載:http://svmiller.com/blog/2016/07/r-markdown-syllabus/首先第一頁是課程的基本信息:講授人,時間,地點,課本材料等我修改了一下對應的代碼換上我的信息:---title: "An introduction
  • R Markdown 詳細使用指南(三)
    在上一次的內容之上,完善 pdf 輸出的相關注意事項:首先,需要明確的是:pandoc 以及 latex 編譯工具,目前都是採用 rmarkdown 包以及 TinyTex 包自帶的方式來完成輸出工作,因此,無需外部編譯環境。
  • RStudio|用R Markdown生成你的R語言數據分析報告
    2,create R Markdown通常而言 .Rmd文檔由 txt文本、嵌入式的R代碼塊以及相應的文檔渲染參數YAML組成。當我們在Rstudio中打開一個.Rmd 文檔並點擊運行時,相應的代碼和運行結果會被同時保存,也可自由插入後續代碼。之後可以由knit將結果通過pandoc轉化為指定的文檔格式。
  • Tidy時代R語言學習的一些ABC
    新年的第一個計劃,寫一個關於R語言數據處理和操作的教程,突出tidyverse出現之後的新方法。下面這篇小文章,給出了一個tidy時代R語言的入門書單和一些網絡資源。不全面,更不權威,就作為這個新教程系列的參考資料吧。
  • 全網通用的markdown文章圖床實現與圖片盜鏈解決方案!
    今天,就為大家介紹一下,全網通用的markdown文章,圖床搭建、遷移方案與代碼實現!隨著越來越多的人開始使用markdown寫作,在對markdown的語法簡潔高效而歡喜的同時,卻對markdown的圖片展示而發愁。如何在markdown中插入圖片,相信已經成為很多人的苦惱所在。
  • markdown寫公眾號
    前言早前進入it這個行業就有寫博客的習慣,之前用的一款百度出的【百度空間】的產品,當時一些文章還有不少的瀏覽量
  • R發布網頁版PPT(1)
    限於筆者經驗,今天我們只涉及ioslides的一些問題。通過Rstudio默認的模板,可以滿足大家通常的需求,簡單的展示是完全沒有問題的,而且前兩種格式支持js輸出的圖形,光是聽起來就有些小激動呢……然而僅僅使用這些功能的話,用不了多久你就會發現似乎展示作品都是那一套,稍顯死板。
  • 在Django中使用Markdown
    照片來自Pexels,由mali maeder拍攝問題像每個網站一樣,我們在主頁、FAQ部分和「關於」頁面等地方都有不同類型的(大部分)靜態內容。很長一段時間以來,我們都是在Django模板中直接管理這些內容的。當我們最終決定是時候將這些內容從模板轉移到資料庫中時,我們認為最好使用Markdown。
  • 最實用的 Markdown 語法教程
    之前我也寫過一篇關於
  • 推薦一款 Nice 的 Markdown工具【Markdown Nice】
    還記得,我第一次聽說 Markdown 是在大二的時候,有一位老師介紹了一些好用的工具,其中就有提到 Markdown ,從此自己無論是做筆記寫文章都在非常熱衷於使用 Markdown 工具。Typora 是一款markdown工具,可線上使用,因為非常的純粹得到擁有廣大的支持者。3 通用語法 3.1 標題在文字寫書寫不同數量的#可以完成不同的標題,如下:一級標題二級標題 三級標題3.2 無序列表無序列表的使用,在符號-後加空格使用。
  • Markdown實時分塊渲染引擎
    起因最近在寫一個博客小網站,使用markdown作為編寫語言。