歡迎關(guān)注天下博客:http://blog.genesino.com/2016/11/bookdown-usage/
Jump to...
bookdown
是著名R包作者謝益輝開發(fā)的厘擂,支持采用Rmarkdown
(R代碼可以運行)或普通markdown
編寫文檔昆淡,然后編譯成HTML
, WORD
, PDF
, Epub
等格式。樣式清新刽严,使用簡單昂灵,值得擁有。
在Bookdown的官網(wǎng)舞萄,有很多免費的用bookdown
寫的R書籍倔既,如Hadley Wickham等撰寫的《R for Data Science》,Roger D. Peng撰寫的《R Programming for Data Science》, 陳總的《液體活檢口袋書》鹏氧,益輝的《R語言忍者秘笈》渤涌,《單細胞數(shù)據(jù)整體分析流程》https://hemberg-lab.github.io/scRNA.seq.course/index.html (初學單細胞分析可以完全照著這個,在學習過程中改進)把还。
還有很多基于Bookdown的教程实蓬,一時也想不起來,歡迎大家補充吊履。我們前面轉(zhuǎn)錄組和R培訓的教案也是用bookdown寫作的安皱,后續(xù)再調(diào)整下格式,出一批電子書和紙質(zhì)書艇炎,有意向和需求的歡迎聯(lián)系酌伊。
下面分2步講述,自己如何構(gòu)建一個Bookdown書籍缀踪,第一部分是通過bookdown示例了解其基本功能和使用居砖,第二部分是個人在使用過程中碰到的問題和解決方式。
基本使用
安裝必須軟件
Rstudio
或Pandoc
二選一, bookdown
必須安裝驴娃。
Install
Rstudio (version>1.0.0)
(安裝和使用見Rstudio)Install
Pandoc (version>1.17.0.2)
或者參照here奏候。如果系統(tǒng)新,可以直接使用系統(tǒng)自帶的yum
或apt-get
唇敞;如果沒有權(quán)限或系統(tǒng)比較老蔗草,Pandoc的安裝可以使用conda,具體配置見Conda配置疆柔,配置好運行conda install -c conda-forge pandoc
即可安裝咒精。In R
install.packages("bookdown")
Demo示例
克隆或下載https://github.com/rstudio/bookdown-demo示例文件,編譯成功后旷档,依葫蘆畫葫蘆修改.
編譯成書
運行下載的示例中的bash _build.sh
模叙,_book
目錄下就是成書.
The content of _build.sh
is:
#!/bin/sh
Rscript -e "bookdown::render_book('index.Rmd', 'bookdown::gitbook')"
# 生成pdf需要安裝好latex,如果不需要可以注釋掉
Rscript -e "bookdown::render_book('index.Rmd', 'bookdown::pdf_book')"
<mark style="box-sizing: border-box;">在前面的內(nèi)容運轉(zhuǎn)起來后彬犯,再看后面的內(nèi)容向楼。</mark>
Customize our bookdown
準備Rmd
文件
基本規(guī)則
一個典型的
bookdown
文檔包含多個章節(jié)查吊,每個章節(jié)在一個R Markdown
文件里面 (文件的語法可以是pandoc
支持的markdown
語法,但后綴必須為Rmd
)湖蜕。每一個章節(jié)都必須以
# Chapter title
開頭逻卖。后面可以跟一段概括性語句,概述本章的內(nèi)容昭抒,方便理解评也,同時也防止二級標題出現(xiàn)在這一頁。默認系統(tǒng)會按照文件名的順序合并Rmd
文件灭返。另外章節(jié)的順序也可在
_bookdown.yml
文件中通過rmd_files:["file1.Rmd", "file2.Rmd", ..]
指定盗迟。如果有
index.Rmd
,index.Rmd
總是出現(xiàn)在第一個位置熙含。通常index.Rmd里面也需要有一章節(jié)罚缕,如果不需要對這一章節(jié)編號的話,可以寫作# Preface {-}
, 關(guān)鍵是{-}
怎静。-
在第一個出現(xiàn)的
Rmd
文件中 (通常是index.Rmd
)邮弹,可以定義Pandoc
相關(guān)的YAML metadata
, 比如標題、作者蚓聘、日期等 (去掉#及其后的內(nèi)容)腌乡。title: "My book"
author: #可以寫多行信息,都會被當做Author處理- "CT"
- "CY"
- "chentong_biology@163.com"
date: "r Sys.Date()
"
documentclass: article #可以為book或article
如果需要引用參考文獻夜牡,則添加下面三行內(nèi)容
bibliography: [database.bib] #指定存儲參考文獻的bib文件与纽,endote或zotero都可以導出這種引文格式
biblio-style: apalike #設(shè)定參考文獻顯示類型
link-citations: yes```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE, fig.align="center", out.width="95%", fig.pos='H') knitr::opts_chunk$set(cache = FALSE, autodep=TRUE) set.seed(0304)
插入并引用圖片(外部圖片)
插入圖片最好使用knitr::include_graphics
,可以同時適配HTML和PDF輸出塘装。另外當目錄下同時存在name1.png
和name1.pdf
文件時急迂,會自動選擇在HTML展示name1.png
文件,在PDF
輸出中引入name1.pdf
格式的文件氢哮。
圖的標簽為fig-name
(不能有下劃線)袋毙,在引用時需使用如下格式\@ref(fig:fig-name)
,且fig.cap
也要設(shè)置內(nèi)容冗尤。
多張圖可以同時展示,圖的名字以vector形式傳給include_graphics
胀溺,需要設(shè)置out.width=1/number-pics
和 fig.show="hold"
裂七。
Insert a single pic and refer as Figure \@ref(fig:fig-name). `echo=FALSE` will hide the code block and display the output of `r` command only. These options can be set globally as indicated below.
```{r fig-name, fig.cap="Markdown supported string as caption", fig.align="center", echo=FALSE}
knitr::include_graphics("images/1.png")
Suppose we have 3 pictures in images
folder with names as Fig1_a
, Fig1_b
, Fig1_c
, we can refer to them using Figure @ref(fig:fig1).
fig1 = list.files("images", pattern="Fig1_.*", full.names=T)
knitr::include_graphics(fig1)
Another way of including two pics.
knitr::include_graphics(c("images/1.png", "images/2.png"))
如果圖或表的標題中有Markdown語法,輸出為HTML時是可以正確解析的仓坞,但是輸出為PDF時卻不可以背零。這時可以使用`Text Reference`。當圖或表的標題太長時无埃,也可以使用`Text Reference`引用一段話作為圖和表的標題徙瓶。
Here is normal text.
(ref:pic-label) This line can be referred in fig.cap and markdown syntax is supported for both HTML
and PDF
output.
knitr::include_graphics("images/1.png")
輸出PDF時不支持使用在線圖片毛雇,可以加一個判斷。
if (!file.exists(cover_file <- 'cover.jpg')){
download.file(url, cover_file, mode = 'wb')
}
knitr::include_graphics(if (identical(knitr:::pandoc_to(), 'html')) url else cover_file)
##### 插入并引用表格(外部表格)
外部表格的名字中必須包含`tab:`, 然后是表格的實際名字侦镇,格式為`(\#tab:table-name)`; 引用時使用`Table \@ref(tab:table-name)`灵疮。 表格名字中不能有下劃線。
Check Table @ref(tab:seq-sum) for detail.
Table: (#tab:seq-sum) Summary of sequencing reads 測序量總結(jié) (對于雙端測序, _1 表示左端reads, _2 表示右端reads)
Sample Total reads Total bases Sequence length (nt) GC content (%) Encoding
T8_1 37,106,941 5,566,036,721 138-150 47 Sanger / Illumina 1.9
T8_2 37,106,941 5,566,034,285 138-150 47 Sanger / Illumina 1.9
##### 插入并引用表格(內(nèi)部表格)
插入表格推薦使用`knitr::kable`壳繁,只要提供數(shù)據(jù)矩陣震捣,用`r`讀取就可以了。
Check Table @ref(tab:table-id) for detail.
a <- as.data.frame(matrix(rnorm(20), nrow=4))
knitr::kable(a, caption="Test table", booktabs=TRUE)
##### 插入腳注
`text^[footnote]` is used to get the footnote.
where type
may be article
, book
, manual
, and so on.^[The type name is case-insensitive, so it does not matter if it is manual
, Manual
, or MANUAL
.]
##### 插入引文
假如我們的`bib`文件中內(nèi)容如下闹炉,如果我們要引用這個文章蒿赢,只要寫 `[@chen_m6a_2015]`就可以了。
@article{chen_m6a_2015,
title = {m6A {RNA} {Methylation} {Is} {Regulated} by {MicroRNAs} and {Promotes} {Reprogramming} to {Pluripotency}},
volume = {16},
issn = {1934-5909, 1875-9777},
url = {http://www.cell.com/cell-stem-cell/abstract/S1934-5909(15)00017-X},
doi = {10.1016/j.stem.2015.01.016},
language = {English},
number = {3},
urldate = {2016-12-08},
journal = {Cell Stem Cell},
author = {Chen, Tong and Hao, Ya-Juan and Zhang, Ying and Li, Miao-Miao and Wang, Meng and Han, Weifang and Wu, Yongsheng and Lv, Ying and Hao, Jie and Wang, Libin and Li, Ang and Yang, Ying and Jin, Kang-Xuan and Zhao, Xu and Li, Yuhuan and Ping, Xiao-Li and Lai, Wei-Yi and Wu, Li-Gang and Jiang, Guibin and Wang, Hai-Lin and Sang, Lisi and Wang, Xiu-Jie and Yang, Yun-Gui and Zhou, Qi},
month = mar,
year = {2015},
pmid = {25683224},
pages = {289--301},
}
#### 準備YML配置文件
##### _bookdown.yml
配置輸入和輸出文件參數(shù)渣触。
book_filename: "輸出文件的名字"
output_dir: "輸出目錄的名字羡棵,默認_book"
language:
ui:
chapter_name: ""
##### _output.yml
配置產(chǎn)生輸出文件的命令行參數(shù)。
bookdown::pdf_book:
template: ehbio.tex #使用自己定制的pandoc latex模板
includes: # or only customize part latex module
in_header: preamble.tex
before_body: latex/before_body.tex
after_body: latex/after_body.tex
latex_engine: xelatex
citation_package: natbib
keep_tex: yes
pandoc_args: --chapters
toc_depth: 3
toc_unnumbered: no
toc_appendix: yes
quote_footer: ["\VA{", "}{}"]
bookdown::epub_book:
stylesheet: css/style.css
bookdown::gitbook:
css: style.css
split_by: section
config:
toc:
collapse: none
before: | #設(shè)置toc開頭和結(jié)尾的鏈接
<li><a ><img src="ehbio_logo.png" width="100%"></a></li>
after: |
<li><a href="mailto:ct@ehbio.com" target="blank">ct@ehbio.com</a></li>
download: [pdf, epub, mobi]
edit: https://github.com/rstudio/bookdown/edit/master/inst/examples/%s
sharing:
twitter: no
github: no
facebook: no
#### 其它定制
* 不同的文件分別用于`html`和`pdf`輸出
```
# in _bookdown.yml
rmd_files:
html: ["index.Rmd", "file2.Rmd"]
latex: ["index_pdf.Rmd", "file3.Rmd"]
# Different render way
#!/bin/sh
Rscript -e "bookdown::render_book('index.Rmd', 'bookdown::gitbook')"
Rscript -e "bookdown::render_book('index_pdf.Rmd', 'bookdown::pdf_book')"
```
* 配置全局變量自適應`HTML`和`PDF`輸出
```
```{r setup, include=FALSE}
library(knitr)
output <- opts_knit$get("rmarkdown.pandoc.to")
html = FALSE
latex = FALSE
opts_chunk$set(echo = FALSE, fig.align="center", fig.show="hold")
if (output=="html") {
html = TRUE
}
if (output=="latex") {
opts_chunk$set(out.width="95%", out.height='0.7\\textheight', out.extra='keepaspectratio', fig.pos='H')
latex = TRUE
}
#knitr::opts_chunk$set(cache = FALSE, autodep=TRUE)
set.seed(0304)
```
Below text will only appear in HTML output.
```{asis, echo=html}
# EHBIO Gene Technology {-}
```
Below command will only be executed and displayed in HTML output.
```{r cover, eval=html, out.width="99%"}
knitr::include_graphics("ehbio/cover.png")
```
```
* 保留生成的markdown文件
```
# add below lines to last Rmd file
```{r, include=FALSE}
file.rename(from="bookdown_file_name.md", to="bookdown_file_name.saved.md")
```
```
* 包含子文件 (subfile.txt)
```
```{r child="subfile.txt"}
```
```
* cahce external file [ref](https://github.com/yihui/knitr/issues/238)
```
```{r mtime-func}
mtime <- function(files){
lapply(Sys.glob(files), function(x) file.info(x)$mtime)
}
```
```{r mtime-usage, cache=T, cache.extra=mtime(c("file1", "file2", file3))}
file3 <- paste0(dir, '/', name)
data1 <- read.table("file1")
data2 <- read.table("file2")
```
```
### 預覽生成的WEB文件
如果沒有安裝Rstudio嗅钻,可以在生成的book目錄(有`index.html`的目錄)下運行`python -m SimpleHTTPServer 11521` (11521為端口號晾腔,一般選較大值避免沖突), 然后就可以在瀏覽器輸入網(wǎng)址`http://server-ip:11521`來訪問了。
### References
* [https://bookdown.org/yihui/bookdown/get-started.html](https://bookdown.org/yihui/bookdown/get-started.html)
* [https://github.com/rstudio/bookdown/tree/master/inst/examples](https://github.com/rstudio/bookdown/tree/master/inst/examples)
* [http://stackoverflow.com/questions/25236850/how-to-set-different-global-options-in-knitr-and-rstudio-for-word-and-html](http://stackoverflow.com/questions/25236850/how-to-set-different-global-options-in-knitr-and-rstudio-for-word-and-html)
* Multiple output with different configs [https://github.com/yihui/knitr/issues/1145](https://github.com/yihui/knitr/issues/1145)
* Multiple output with different configs [https://github.com/yihui/knitr/issues/114://github.com/rstudio/rmarkdown/issues/614](https://github.com/yihui/knitr/issues/114://github.com/rstudio/rmarkdown/issues/614)
* Citation style [http://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html](http://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html)
* Save markdown [http://stackoverflow.com/questions/19989325/knit-rmd-file-to-md-and-save-the-md-file-one-level-up-with-a-different-name](http://stackoverflow.com/questions/19989325/knit-rmd-file-to-md-and-save-the-md-file-one-level-up-with-a-different-name)
* PDF online pic [http://www.pzhao.org/zh/post/bookdown-tips/](http://www.pzhao.org/zh/post/bookdown-tips/)
<footer class="entry-meta" style="box-sizing: border-box; display: block; font-size: 0.75rem; text-transform: uppercase; color: rgba(187, 187, 187, 0.8); margin: 50px 30px 30px; text-align: center; font-family: Lato, Calibri, Arial, sans-serif; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">[BOOKDOWN](http://blog.genesino.com/tags#bookdown "Pages tagged bookdown")CHENTONG
版權(quán)聲明:本文為博主原創(chuàng)文章啊犬,轉(zhuǎn)載請注明出處灼擂。
![alipay.png](http://upload-images.jianshu.io/upload_images/7071112-57379e41a56e560f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![WeChatPay.png](http://upload-images.jianshu.io/upload_images/7071112-a4f1708f9375dc76.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
</footer>