-
-
Notifications
You must be signed in to change notification settings - Fork 522
/
12-bookdown.Rmd
356 lines (235 loc) · 15.7 KB
/
12-bookdown.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# Books
We have introduced the basics of R Markdown in Chapter \@ref(documents), which highlighted how HTML, PDF, and Word documents can be produced from an R workflow. However, larger projects can become difficult to manage in a single R Markdown file. The **bookdown** package\index{bookdown} [@xie2016; @R-bookdown] addresses this limitation, and offers several key improvements:
- Books and reports can be built from multiple R Markdown files.
- Additional formatting features are added, such as cross-referencing, and numbering of figures, equations, and tables.
- Documents can easily be exported in a range of formats suitable for publishing, including PDF, e-books and HTML websites.
This book itself was created using **bookdown**, and acts as an example of what can be achieved. Despite the name containing the word "book", **bookdown** is not only for books, and it can be used for long reports, dissertations, or even single R Markdown documents (see Section \@ref(a-single-document)). It also works with other computing languages such as Python and C++ (see Section \@ref(language-engines)). If you want, you can even write documents irrelevant to computing, such as a novel.
In this chapter, we cover the basics of **bookdown**, and explain how to start a **bookdown** project. Much of the the content is based on the work "*bookdown: Authoring Books and Technical Documents with R Markdown*" (https://bookdown.org/yihui/bookdown/) of @xie2016, which provides more detailed explanations of the concepts highlighted.
## Get started {#bookdown-start}
You can install either the CRAN version or the development version on GitHub (https://github.com/rstudio/bookdown):
```{r eval=FALSE}
# install from CRAN
install.packages('bookdown')
# or GitHub
devtools::install_github('rstudio/bookdown')
```
If you use RStudio, you can start a new bookdown project from the menu `File -> New Project -> New Directory -> Book Project using bookdown`.^[Alternatively, the command `bookdown:::bookdown_skeleton(getwd())` will create a skeleton project in your current working directory.] Open the R Markdown file `index.Rmd`, and click the button `Build Book` on the `Build` tab of RStudio. This will compile the book and display the HTML version within the RStudio Viewer, which looks like Figure \@ref(fig:bookdown-template).
```{r bookdown-template, echo=FALSE, fig.cap= "The HTML output of the bookdown template.", out.width='100%'}
knitr::include_graphics("images/bookdown-template.png", dpi = NA)
```
You may add or change the R Markdown files, and hit the `Knit` button again to preview the book. If you prefer not to use RStudio, you may also compile the book through the command line using `bookdown::render_book()`.
## Project structure {#bookdown-project}
Below shows the basic structure of a default **bookdown** project:
```markdown
directory/
├── index.Rmd
├── 01-intro.Rmd
├── 02-literature.Rmd
├── 03-method.Rmd
├── 04-application.Rmd
├── 05-summary.Rmd
├── 06-references.Rmd
├── _bookdown.yml
├── _output.yml
├── book.bib
├── preamble.tex
├── README.md
└── style.css
```
As a summary of these files:
- `index.Rmd`: This is the only Rmd document to contain a YAML frontmatter as described within Chapter \@ref(basics), and is the first book chapter.
- Rmd files: A typical **bookdown** book contains multiple chapters, and each chapter lives in one separate Rmd file.
- `_bookdown.yml`: A configuration file for **bookdown**.
- `_output.yml`: It specifies the formatting of the HTML, LaTeX/PDF, and e-books.
- `preamble.tex` and `style.css`: They can be used to adjust the appearance and styles of the book output document(s). Knowledge of LaTeX and/or CSS is required.
These files are explained in greater detail in the following subsections.
### Index file
The `index.Rmd` file contains the first chapter and the YAML metadata, e.g.,
```yaml
---
title: "A Minimal Book Example"
author: "Yihui Xie"
date: "`r "\x60r Sys.Date()\x60"`"
site: bookdown::bookdown_site
documentclass: book
bibliography: [book.bib, packages.bib]
biblio-style: apalike
link-citations: yes
description: "This is a minimal example of using
the bookdown package to write a book."
---
```
### Rmd files
By default, all Rmd files are merged with the `index.Rmd` to render the book. The Rmd files must start immediately with the chapter title using the first-level heading, e.g., `# Chapter Title`. Note that YAML metadata should not be included in these Rmd files, as it is inherited from the `index.Rmd` file.
- 01-intro.Rmd
```markdown
# Introduction
This chapter is an overview of the methods that
we propose to solve an **important problem**.
```
- 02-literature.Rmd
```markdown
# Literature
Here is a review of existing methods.
```
By default, **bookdown** merges all Rmd files by the order of filenames, e.g., `01-intro.Rmd` will appear before `02-literature.Rmd`. Filenames that start with an underscore `_` are skipped.
### `_bookdown.yml`
The `_bookdown.yml` file allows you to specify optional settings to build the book. For example, you may want to override the order in which files are merged by including the field `rmd_files`:
```yaml
rmd_files: ["index.Rmd", "02-literature.Rmd", "01-intro.Rmd"]
```
### `_output.yml`
The `_output.yml` file is used to specify the book output formats (see Section \@ref(bookdown-output)). Here is a brief example:
```yaml
bookdown::gitbook:
lib_dir: assets
split_by: section
config:
toolbar:
position: static
bookdown::pdf_book:
keep_tex: yes
bookdown::html_book:
css: toc.css
```
## Markdown extensions {#bookdown-markdown}
The **bookdown** package expands upon the Markdown syntax\index{Markdown syntax} outlined in Section \@ref(markdown-syntax), and provides additional powerful features that assist longer documents and academic writing.
### Number and reference equations {#equations}
Section \@ref(math-expressions) highlighted how equations can be created using LaTeX syntax within Markdown. To number equations, put them in the `equation` environments, and assign labels to them using the syntax `(\#eq:label)`. Equation labels must start with the prefix `eq:` in **bookdown**. For example:
```latex
\begin{equation}
E=mc^2
(\#eq:emc)
\end{equation}
```
It renders the equation below \@ref(eq:emc):
\begin{equation}
E=mc^2
(\#eq:emc)
\end{equation}
### Theorems and proofs {#theorems}
Theorems and proofs provide environments that are commonly used within articles and books in mathematics. To write a theorem, you can use the syntax below:
````markdown
`r ''````{theorem, label, name="Theorem name"}
Here is my theorem.
```
````
For example:
```{theorem, pyth, name="Pythagorean theorem"}
For a right triangle, if $c$ denotes the length of the hypotenuse
and $a$ and $b$ denote the lengths of the other two sides, we have
$$a^2 + b^2 = c^2$$
```
Theorems can be numbered and cross-referenced, as you can see from Theorem \@ref(thm:pyth). The `proof` environment behaves similarly to theorem environments but is unnumbered.
Variants of the `theorem` environments include: `r knitr::combine_words(names(bookdown:::theorem_abbr[-1]), before = '\x60')`. The abbreviations for references (e.g. `\@ref(lem:mylemma)`) are respectively `r knitr::combine_words(unlist(bookdown:::theorem_abbr[-1]), before = '\x60')`.
Variants of the `proof` environments include `r knitr::combine_words(names(bookdown:::label_names_math2[-1]), before = '\x60')`. The syntax for these environments is similar to the `theorem` environment, e.g., ```` ```{lemma}````.
### Special headers
There are two special types of first-level headers than can be used in **bookdown**:
- A part can be created using `# (PART) Part Title {-}` before the chapters that belong to this part.
- Appendices `# (APPENDIX) Appendix {-}`: All chapters after this header will be treated as the appendix. The numbering style of these chapters will be `A`, `B`, `C`, etc., and sections will be numbered as `A.1`, `A.2`, and so on.
### Text references
A text reference is a paragraph with a label. The syntax is `(ref:label) text`, where `label` is a unique identifier, and `text` is a Markdown paragraph. For example:
```markdown
(ref:foo) Define a text reference **here**.
```
Then you can use `(ref:foo)` to refer to the full text. Text references can be used anywhere in the document, and are particularly useful when assigning a long caption to a figure or including Markdown formatting in a caption. For example:
````markdown
Some text.
(ref:cool-plot) A boxplot of the data `iris` in **base** R.
`r ''````{r cool-plot, fig.cap='(ref:cool-plot)'}
boxplot(Sepal.Length ~ Species, data = iris)
```
````
### Cross referencing
The **bookdown** package extends cross-referencing in R Markdown documents and allows section headers, tables, figures, equations, and theorems to be cross-referenced automatically. This only works for numbered environments, and therefore requires figures and tables to be assigned a label. Cross-references are made in the format `\@ref(type:label)`, where `label` is the chunk label and `type` is the environment being referenced. As examples:
- Headers:
```markdown
# Introduction {#intro}
This is Chapter \@ref(intro)
```
- Figures:
````markdown
See Figure \@ref(fig:cars-plot)
`r ''````{r cars-plot, fig.cap="A plot caption"}
plot(cars) # a scatterplot
```
````
- Tables:
````markdown
See Table \@ref(tab:mtcars)
`r ''````{r mtcars}
knitr::kable(mtcars[1:5, 1:5], caption = "A caption")
```
````
- Theorems:
````markdown
See Theorem \@ref(thm:boring)
`r ''````{theorem, boring}
Here is my theorem.
```
````
- Equations:
````markdown
See equation \@ref(eq:linear)
\begin{equation}
a + bx = c (\#eq:linear)
\end{equation}
````
Note that only alphanumeric characters (`a-z`, `A-Z`, `0-9`), `-`, `/`, and `:` are allowed in these labels.
## Output Formats {#bookdown-output}
The **bookdown** package includes the following output formats\index{output formats}:
- HTML:
- `gitbook`
- `html_book`
- `tufte_html_book`
- PDF:
- `pdf_book`
- e-book:
- `epub_book`
- Single documents:
- `html_document2`
- `tufte_html2`
- `pdf_document2`
- `tufte_handout2`
- `tufte_book2`
- `word_document2`
### HTML
Although multiple formats are available for HTML books in **bookdown**, we will focus on the Gitbook style, which appears to be the most popular format. It provides a clean style, with a table of contents on the left. The design is fully responsive to make the content suitable for both mobile and desktop devices.
The output format `bookdown::gitbook` is built upon `rmarkdown::html_document`, which was explained in Section \@ref(html-document). The main difference between rendering in R Markdown and **bookdown** is that a book will generate multiple HTML pages by default. To change the way the HTML pages are split, the `split_by` argument can be specified. This defaults to `split_by: chapter`, but readers may prefer to use `split_by: section` if there are many sections within chapters, in which case a chapter page may be too long.
### LaTeX/PDF
There are limited differences between the output of `pdf_book()` in **bookdown** compared to `pdf_document()` in **rmarkdown**. The primary purpose of the new format is to resolve the labels and cross-references written in the syntax described in Section \@ref(cross-referencing).
Pandoc supports LaTeX commands in Markdown. Therefore if the only output format that you want for a book is LaTeX/PDF, you may use the syntax specific to LaTeX, such as `\newpage` to force a page break. A major disadvantage of this approach is that LaTeX syntax is not portable to other output formats, meaning that these changes will not be transferred to the HTML or e-book outputs.
### E-books
The e-book formats can be read on devices like smartphones, tablets, or special e-readers such as Kindle. You can create an e-book of the EPUB format with `bookdown::epub_book`.
### A single document
We highlighted in Section \@ref(bookdown-markdown) that **bookdown** extends the syntax provided by R Markdown, allowing automatic numbering of figures / tables / equations, and cross-referencing them. You may use **bookdown** within single-file R Markdown documents to benefit from these features. The functions `html_document2()`, `tufte_html2()`, `pdf_document2()`, `word_document2()`, `tufte_handout2()`, and `tufte_book2()` are designed for this purpose. To use this in a traditional R Markdown document, you can replace the output YAML option as follows:
````yaml
---
title: "Document Title"
output: bookdown::pdf_document2
---
````
## Editing {#bookdown-edit}
In this section, we explain how to edit, build, preview, and serve the book locally.
### Build the book
To build all Rmd files into a book, you can call the function `bookdown::render_book()`. It uses the settings specified in the `_output.yml` (if it exists). If multiple output formats are specified in it, all formats will be built. If you are using RStudio, this can be done through the `Build` tab. Open the drop down menu `Build Book` if you only want to build one format.
(ref:bookdown-build) The `Build` tab within RStudio highlighting **bookdown** output formats.
```{r bookdown-build, echo=FALSE, fig.cap="(ref:bookdown-build)", out.width='90%', fig.align='center'}
knitr::include_graphics("images/bookdown-build.png", dpi = NA)
```
### Preview a chapter
Building the whole book can be slow when the size of the book is big or your book contains large amounts of computation. We can use the `preview_chapter()` function in **bookdown** to only build a single chapter at a time. Equivalently, you can click the `Knit` button in RStudio.
### Serve the book
Instead of running `render_book()` or `preview_chapter()` each time you want to view the changes, you can use the function `bookdown::serve_book()` to start a live preview of the book. Any time a Rmd file is saved, the book will be recompiled automatically, and the preview will be updated to reflect the changes.
### RStudio addins
The **bookdown** package comes with two addins for RStudio which assist the editing of books:
- "Preview Book": this calls `bookdown::serve_book()` to compile and serve the book.
- "Input LaTeX Math": provides a text box which allows you to write LaTeX equations, to avoid common errors when typing the raw LaTeX math expressions.
## Publishing {#bookdown-publish}
You can generate books for both physical and electronic distribution. This section outlines some of the main options.
### RStudio Connect
The easiest way to publish books online is through https://bookdown.org, which is a website provided by RStudio to host your books for free. Books can be pushed to this website by using `bookdown::publish_book()`. You will need to sign up for an account at https://bookdown.org/connect/, and your login details will be used to authorize **bookdown** the first time you call the `publish_book()` function.
### Other services
You can host your book online with many other web services, such as Netlify or GitHub (via [GitHub Pages](https://pages.github.com)). Because the output from `bookdown::render_book()` is a collection of static files, you can host them using the same methods of hosting normal web pages.
### Publishers
You can consider publishing physical copies of your book with a publisher or using self-publishing. Many publishers provide LaTeX style classes that can be used to set the overall appearance of the book, and these can be used easily by setting the `documentclass` option in the YAML metadata of `index.Rmd`. Further customization of the appearance of the PDF book can be achieved by altering the LaTeX preamble via the `includes: in_header` option of `bookdown::pdf_book`.