-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
02-rmd-basics-markdown.Rmd
298 lines (206 loc) · 12.8 KB
/
02-rmd-basics-markdown.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
---
#########################################
# options for knitting a single chapter #
#########################################
output:
bookdown::pdf_document2:
template: templates/template.tex
bookdown::html_document2: default
bookdown::word_document2: default
documentclass: book
#bibliography: [bibliography/references.bib, bibliography/additional-references.bib]
---
```{block type='savequote', quote_author='(ref:cicero-quote)', include=knitr::is_latex_output()}
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...
There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain...
```
(ref:cicero-quote) --- Cicero's *de Finibus Bonorum et Malorum*.
<!--
Notes for adding an opening quote in PDF output:
i) add the reference for the quote with the chunk option quote_author="my author name",
ii) include=knitr::opts_knit$get('rmarkdown.pandoc.to') == 'latex' means that these quotes are only included when output is latex (in HTML output, it would appear by the end of the previous page)
iii) You can't use markdown syntax inside chunk options, so if you want to e.g. italicise a book name in the quote reference use a 'text reference': Create a named piece of text with '(ref:label-name) My text', then link to this in the chunk option with quote_author='(ref:label-name)'
-->
# R Markdown basics {#rmd-basics}
\minitoc <!-- this will include a mini table of contents-->
<!-- LaTeX normally does not indent the first line after a heading - however, it does so after the mini table of contents. You can manually tell it not to with \noindent -->
\noindent Here is a brief introduction to using *R Markdown*.
*Markdown* is a simple formatting syntax for authoring HTML, PDF, and MS Word documents and much, much more.
*R Markdown* provides the flexibility of *Markdown* with the implementation of **R** input and output. For more details on using *R Markdown* see <http://rmarkdown.rstudio.com>.
## Basic markdown syntax
### Whitespace
Be careful with your spacing.
While whitespace largely is ignored, it does at times give markdown signals as to how to proceed.
As a habit, try to keep everything left aligned whenever possible, especially as you type a new paragraph.
In other words, there is no need to indent basic text in the Rmd document (in fact, it might cause your text to do funny things if you do).
### Italics and bold
- *Italics* are done like \*this\* or \_this\_
- **Bold** is done like \*\*this\*\* or \_\_this\_\_
- **_Bold and italics_** is done like \*\*\*this\*\*\*, \_\_\_this\_\_\_, or (the most transparent solution, in my opinion) \*\*\_this\_\*\*
### Inline code
- `Inline code` is created with backticks like `` `this` ``
### Sub and superscript
Sub~2~ and super^2^ script is created like this\~2\~ and this\^2\^
### Strikethrough
- ~~Strikethrough~~ is done \~\~like this\~\~
### 'Escaping' (aka "What if I need an actual asterisk?")
- To include an actual \*, \_ or \\, add another \\ in front of them: \\\*, \\\_, \\\\
### Endash (--), emdash (---)
- -- and --- with \-\- and \-\-\-
### Blockquotes
Do like this:
> Put a \> in front of the line.
### Headings
Section headers are created with \#'s of increasing number, i.e.
- \# First-level heading
- \#\# Second-level heading
- \#\#\# Etc.
In PDF output, a level-five heading will turn into a paragraph heading, i.e. `\paragraph{My level-five heading}`, which appears as bold text on the same line as the subsequent paragraph.
### Lists
Unordered list by starting a line with an \* or a \-:
* Item 1
* Item 2
Ordered lists by starting a line with a number.
Notice that you can mislabel the numbers and *Markdown* will still make the order right in the output:
1. Item 1
4. Item 2
To create a sublist, indent the values a bit (at least four spaces or a tab):
1. Item 1
1. Item 2
1. Item 3
- Item 3a
- Item 3b
### Line breaks
The official *Markdown* way to create line breaks is by ending a line with more than two spaces.
Roses are red.
Violets are blue.
This appears on the same line in the output, because we didn't add spaces after red.
Roses are red.
Violets are blue.
This appears with a line break because I added spaces after red.
I find this is confusing, so I recommend the alternative way: Ending a line with a backslash will also create a linebreak:
Roses are red.\
Violets are blue.
To create a new paragraph, you put a blank line.
Therefore, this line starts its own paragraph.
### Hyperlinks
- [This is a hyperlink](https://www.google.com) created by writing the text you want turned into a clickable link in `[square brackets followed by a](https://hyperlink-in-parentheses)`
### Footnotes
- Are created^[my footnote text] by writing either \^[my footnote text] for supplying the footnote content inline, or something like `[^a-random-footnote-label]` and supplying the text elsewhere in the format shown below [^test-footnote]:
`[^a-random-footnote-label]: This is a random test.`
[^test-footnote]: This is a random test.
### Comments
To write comments within your text that won't actually be included in the output, use the same syntax as for writing comments in HTML. That is, \<!\-\- this will not be included in the output \-\->.
<!-- It is super useful to use comments! -->
### Math
The syntax for writing math is stolen from LaTeX. To write a math expression that will be shown **inline**, enclose it in dollar signs.
- This: \$A = \\pi*r^{2}\$ Becomes: $A = \pi*r^{2}$
To write a math expression that will be shown in a block, enclose it in two dollar signs.\
This: `r ifelse(knitr::opts_knit$get('rmarkdown.pandoc.to') == 'latex', "\\$\\$A = \\\\pi*r^{2}\\$\\$", "<span>$</span>\\$A = \\\\pi*r^{2}\\$\\$")`
Becomes:
$$A = \pi*r^{2}$$
To create numbered equations, put them in an 'equation' environment and give them a label with the syntax `(\#eq:label)`, like this:
```latex
\begin{equation}
f\left(k\right) = \binom{n}{k} p^k\left(1-p\right)^{n-k}
(\#eq:binom)
\end{equation}
```
Becomes:
\begin{equation}
f\left(k\right)=\binom{n}{k}p^k\left(1-p\right)^{n-k}
(\#eq:binom)
\end{equation}
For more (e.g. how to theorems), see e.g. the documentation on [bookdown.org](https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html#equations)
## Executable code chunks {#code}
The magic of R Markdown is that we can add executable code within our document to make it dynamic.
We do this either as *code chunks* (generally used for loading libraries and data, performing calculations, and adding images, plots, and tables), or *inline code* (generally used for dynamically reporting results within our text).
The syntax of a code chunk is shown in Figure \@ref(fig:chunk-parts).
```{r chunk-parts, echo=FALSE, fig.cap="Code chunk syntax", out.width="100%", message=FALSE, fig.pos='H'}
library(tidyverse)
knitr::include_graphics("figures/sample-content/chunk-parts.png")
```
Common chunk options include (see e.g. [bookdown.org](https://bookdown.org/yihui/rmarkdown/r-code.html)):
- `echo`: whether or not to display code in knitted output
- `eval`: whether or to to run the code in the chunk when knitting
- `include`: whether to include anything from the from a code chunk in the output document
- `fig.cap`: figure caption
- `fig.scap`: short figure caption, which will be used in the 'List of Figures' in the PDF front matter
**IMPORTANT**: Do *not* use underscoores in your chunk labels - if you do, you are likely to get an error in PDF output saying something like "! Package caption Error: \\caption outside float".
### Setup chunks - setup, images, plots
An R Markdown document usually begins with a chunk that is used to **load libraries**, and to **set default chunk options** with `knitr::opts_chunk$set`.
In your thesis, this will probably happen in **index.Rmd** and/or as opening chunks in each of your chapters.
````
`r ''````{r setup, include=FALSE}
# don't show code unless we explicitly set echo = TRUE
knitr::opts_chunk$set(echo = FALSE)
library(tidyverse)
```
````
### Including images
Code chunks are also used for including images, with `include_graphics` from the `knitr` package, as in Figure \@ref(fig:oxford-logo)
```{r oxford-logo, fig.cap="Oxford logo", out.width='50%', fig.align='center'}
knitr::include_graphics("figures/sample-content/beltcrest.png")
```
Useful chunk options for figures include:
- `out.width` (use with a percentage) for setting the image size
- if you've got an image that gets waaay to big in your output, it will be constrained to the page width by setting `out.width = "100%"`
#### Figure rotation {-}
You can use the chunk option `out.extra` to rotate images.
The syntax is different for LaTeX and HTML, so for ease we might start by assigning the right string to a variable that depends on the format you're outputting to:
```{r}
if (knitr::is_latex_output()){
rotate180 <- "angle=180"
} else {
rotate180 <- "style='transform:rotate(180deg);'"
}
```
Then you can reference that variable as the value of `out.extra` to rotate images, as in Figure \@ref(fig:oxford-logo-rotated).
```{r oxford-logo-rotated, out.extra=rotate180, fig.cap="Oxford logo, rotated", out.width='50%', fig.align='center', echo=FALSE}
knitr::include_graphics("figures/sample-content/beltcrest.png")
```
### Including plots
Similarly, code chunks are used for including dynamically generated plots.
You use ordinary code in R or other languages - Figure \@ref(fig:cars-plot) shows a plot of the `cars` dataset of stopping distances for cars at various speeds (this dataset is built in to **R**).
```{r cars-plot, fig.cap = "A ggplot of car stuff"}
cars %>%
ggplot() +
aes(x = speed, y = dist) +
geom_point()
```
Under the hood, plots are included in your document in the same way as images - when you build the book or knit a chapter, the plot is automatically generated from your code, saved as an image, then included into the output document.
### Including tables
Tables are usually included with the `kable` function from the `knitr` package.
Table \@ref(tab:cars-table) shows the first rows of that cars data - read in your own data, then use this approach to automatically generate tables.
```{r cars-table}
cars %>%
head() %>%
knitr::kable(caption = "A knitr kable table")
```
- Gotcha: when using [`kable`](https://www.rdocumentation.org/packages/knitr/versions/1.21/topics/kable), captions are set inside the `kable` function
- The `kable` package is often used with the [`kableExtra`](https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html) package
### Control positioning
One thing that may be annoying is the way *R Markdown* handles "floats" like tables and figures.
In your PDF output, LaTeX will try to find the best place to put your object based on the text around it and until you're really, truly done writing you should just leave it where it lies.
In general, you should allow LaTeX to do this, but if you really *really* need a figure to be positioned where you put in the document, then you can make LaTeX attempt to do this with the chunk option `fig.pos="H"`, as in Figure \@ref(fig:oxford-logo-controlled):
```{r oxford-logo-controlled, fig.cap="An Oxford logo that LaTeX will try to place at this position in the text", out.width='50%', fig.align='center', fig.pos="H"}
knitr::include_graphics("figures/sample-content/beltcrest.png")
```
As anyone who has tried to manually play around with the placement of figures in a Word document knows, this can have lots of side effects with extra spacing on other pages, etc.
Therefore, it is not generally a good idea to do this - only do it when you really need to ensure that an image follows directly under text where you refer to it (in this document, I needed to do this for Figure \@ref(fig:latex-font-sizing) in section \@ref(max-power)).
For more details, read the relevant section of the [R Markdown Cookbook](https://bookdown.org/yihui/rmarkdown-cookbook/figure-placement.html).
## Executable inline code
'Inline code' simply means inclusion of code inside text.
The syntax for doing this is ``` ``r ''`r R_CODE` ```
For example, ``` ``r ''`r 4 + 4` ``` will output `r 4 + 4` in your text.
You will usually use this in parts of your thesis where you report results - read in data or results in a code chunk, store things you want to report in a variable, then insert the value of that variable in your text.
For example, we might assign the number of rows in the `cars` dataset to a variable:
```{r}
num_car_observations <- nrow(cars)
```
We might then write:\
"In the `cars` dataset, we have ``` ``r ''`r num_car_observations` ``` observations."
Which would output:\
"In the `cars` dataset, we have `r num_car_observations` observations."
## Executable code in other languages than R
If you want to use other languages than R, such as Python, Julia C++, or SQL, see [the relevant section of the *R Markdown Cookbook*](https://bookdown.org/yihui/rmarkdown-cookbook/other-languages.html)