-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.Rmd
More file actions
327 lines (270 loc) · 17.6 KB
/
example.Rmd
File metadata and controls
327 lines (270 loc) · 17.6 KB
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
---
title: "Example APA-style documents generated by R Markdown"
doctype: jou # this can be stu, jou, doc, or man -- try each out!
author:
- name: "Justin Dainer-Best"
# affiliation_number: 1
# - name: "Second Author"
# affiliation_number: 2
# - name: "Third Author"
# affiliation_number: "2,3"
# - name: "Fourth Author"
# affiliation_number: 1
affiliations:
- "Bard College"
# - "Other Institution"
# - "Yet another Institution"
shorttitle: "Example R Markdown APA doc"
leftheader: "Dainer-Best et al."
authors_note: |
This is an author's note; you could
remove it if not desired. You
could include a corresponding
author, and their email.
abstract: "This is an example of creating an approximately APA-style manuscript using R Markdown and .bib files"
keywords: "LaTeX, RMarkdown, Document formatting"
date: "`r format(Sys.time(), '%B %d, %Y')`" # This print's today's date
output:
pdf_document:
toc_depth: 1
template: "template.tex"
keep_tex: true
extra_dependencies: "subfig"
bibliography: example.bib
link-citations: true
csl: apa.csl
# for `doctype: stu`
professor: "Prof. Dainer-Best"
course: "PSY XXX"
duedate: "March, 2021"
---
```{r, echo = FALSE}
# by setting echo=FALSE, this code will not be printed in the output PDF
# by setting the opts_chunk below, no code will be printed, in fact!
# (and neither will messages of warning/notification)
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```
This is a simple example of using R Markdown documents to create APA-formatted documents with LaTeX compiling them into PDFs. You will need to install a version of LaTeX to compile; if you do not have one, you'll find information about using [TinyTeX](https://yihui.org/tinytex/) [@xie2019] for this purpose [here](https://bookdown.org/yihui/rmarkdown-cookbook/install-latex.html). Before installing TinyTeX, I recommend ensuring that you have up-to-date versions of [RStudio](https://www.rstudio.com/products/rstudio/download/), [R](https://cran.r-project.org/), and (if you're using a Windows computer) [Rtools](https://cran.r-project.org/bin/windows/Rtools/).
Then, install the {_tinytex_} package and use it to install TinyTeX:
```
install.packages('tinytex')
tinytex::install_tinytex()
```
After installation, you may need to install the `apa7` LaTeX package [@weiss2021] with the command `tinytex::tlmgr_install("apa7")` -- I have tested this on a Windows computer (RStudio version 1.4.1106; R Version 4.0.5) and seen that it will install the relevant package; however, knitting the document for the first time will also result in the installation of other missing packages. (For more information, [see here](https://bookdown.org/yihui/rmarkdown-cookbook/install-latex-pkgs.html).)
If TinyTeX does not work for you or if you intend to use LaTeX for other work, you may want to install [MacTeX](http://tug.org/mactex/) for Macs or [MiKTeX](https://miktex.org/) for PCs. (These are large installations---thus the point of a "tiny" version.)
You will also have to compile your references in a bibliography. Most folks recommend using Zotero, as do I (manually maintaining references can be frustrating); you'll need to output your references to a .bib file. Document/article titles will follow the capitalization you've got---use APA style yourself! (The most recent versions of R Markdown can also [help add your references](https://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html), including just from a DOI link.)
Some packages [e.g., {[papaja](https://github.com/crsh/papaja)}, @austbarth2020] will create APA-draft manuscripts, but may introduce extra details beyond the basic style. ({_papaja_} is also not currently updated for APA-7.) The style I lay out here will simply create a document using APA formatting of references.
# Why would I want to use this template?
You might think it's fun to lay your document out in R Markdown! You might also want to report the results of tests directly into your document, or include graphs. You might also be procrastinating finishing a paper, and that's fine, too.
I make no promises that this document will help you achieve "perfect" APA style---you'll need to double-check everything, especially your references. (In particular, if you are a student, make sure that this style conforms to any course/assignment requirements.)
# Getting started
You will need to download the `apa.csl` and `template.tex` documents into a directory where your Rmd file lives. Open (or create) your R Markdown document.
Your document will automatically include some YAML headers:
```
---
title: "Your title"
author: "Your name"
date: "3/29/2021"
output: pdf_document
---
```
You can keep the title and date, but you will need to update the others headers to include some of the following YAML headers in your R Markdown document. In particular, you must include the `doctype`, the full set of `output` parameters (`output: pdf_document: template: "template.tex"`), and the `bibliography` and `csl` lines. The others, including `shorttitle` and `leftheader`, `authors_note`, and so forth, are implemented in APA style documents.
```
---
doctype: man # this can be stu, jou, doc, or man
title: "Your title"
author:
- name: "Your name"
affiliation_number: 1
affiliations: "Your affiliation"
shorttitle: "APA short title"
authors_note: |
This is an author's note;
you could remove it if not desired.
abstract: "Your article's abstract"
keywords: "example, keywords"
date: "3/29/21"
output:
pdf_document:
template: "template.tex"
bibliography: example.bib # your .bib file
csl: apa.csl
---
```
A minimal example is included (minimal_example.Rmd and minimal_example.pdf) with these headers; feel free to download it and adapt. Without any changes, knitting it in R Markdown will make the PDF you can see here, so long as you have installed LaTeX---and downloaded the template.tex and apa.csl files into the same directory. (How to knit? Hit the "Knit" button in R Studio with the Rmd file open, or hit CMD+Shift+K / Ctrl+Shift+K.)
If you look at example.Rmd, you'll see how to include multiple authors with differing affiliations. List each author separately. Including `affiliation_number` will provide a superscript number after that name, which then anticipates a subsequent item under `affiliations`. (With only one affiliation, you do not need to include any `affiliation_number`. For each `affiliation_number`, there should be an affiliation listed as `affiliations`.) If an author has multiple affiliations, simply enclose the numbers in quotation marks, as below, separated with a comma: "2,3".
```
author:
- name: "First Author"
affiliation_number: 1
- name: "Second Author"
affiliation_number: 2
- name: "Third Author"
affiliation_number: "2,3"
- name: "Fourth Author"
affiliation_number: 1
affiliations:
- "First Institution"
- "Other Institution"
- "Yet another Institution"
```
As described below, there are some additional headers you may include:
* `leftheader`: The authors' last names (for `jou` doctype only)
* For the `stu` doctype, info about the course: `professor`, `course`, and `duedate`
There are additional YAML headers often used for different documents in R Markdown, many of which may work here.
# Document types
The **{apa7}** document class in LaTeX accepts four document types---they're mentioned briefly above under `doctype`; you can try each out. Here's what they are:
* _jou_: journal style; intended to mimic what a journal looks like (two columns, etc). This will look weird with the minimal_example file---it looks better with a longer file -- this will also make use of the YAML `leftheader` and `shorttitle`, which will alternate page headers.
* _doc_: a one-column PDF output with APA style (including abstract, etc); it will try to be the "easiest to read"
* _man_: APA's suggestion for how to submit documents to a journal---what many instructors ask for in college course, with double-spacing and so forth
* _stu_: student papers---includes YAML headers `professor`, `course`, and `duedate`; otherwise much like `man`
I've created versions of this Rmd file with each document style, so you can see what they might look like.
# Writing in an R Markdown file
Now that you have a working R Markdown file, you've chosen a document type, and you've updated it with your paper title and name, etc., your focus is on writing the document!
If you've ever looked into LaTeX document writing, this is more simple. There are three major things to keep in mind:
1. Use \# to start a section, \## to start a subsection, etc.
2. Use square brackets [] to enclose references, e.g., `[@referencekey]`, where you precede a key with the @ symbol. The "reference key" is the way it will be referred in your .bib file---in example.bib, for example, you'll see that it's the first word of each entry. For more info on citations, [see here](https://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html#citations).
Most other formatting will be done for you. If you want to learn things about formatting in R Markdown, there are a variety of [cheatsheets](https://rmarkdown.rstudio.com/lesson-15.html) available; you can refer to the example.Rmd document here to learn about links, lists, _italics_ or **bold-face text**, etc.
# Including plots
As above, you can refer to the R Markdown cheatsheets to learn how to include pre-existing images. If you'd like to include *plots*, it's as easy as including a code chunk and using R code to create the figure (this uses the {_palmerpenguins_} and {_ggplot2_} packages by @horst2020 and @wickham2016, respectively, and code from the first.) Including `echo=FALSE, warning=FALSE` means that the plot is printed but the code is not. If `echo` were TRUE, the code would also be printed.
R Markdown and LaTeX will try their best to fit the plot into the space allotted to it; you can play around with size by specifying an `out.width` in percentages or inches, as I show here. You may read about more options [here](https://bookdown.org/yihui/rmarkdown/pdf-document.html#figure-options-1), but note that full-page figures may be difficult when `doctype` is set as `jou`. (But see more below.)
The below code produces the figure included in this document. Note that LaTeX places figures as best as it can---sometimes on a subsequent page. I abbreviate the figure caption in the code example:
````
```{r, fig.cap="Cap", out.width="100%"}`r ''`
library(palmerpenguins); library(ggplot2)
ggplot(penguins, aes(x = flipper_length_mm,
y = body_mass_g)) +
geom_point(aes(color = species,
shape = species),
size = 3,
alpha = 0.8) +
theme_minimal() +
scale_color_manual(values = c("darkorange",
"purple",
"cyan4")) +
labs(title = "Penguin size, Palmer Station
LTER",
x = "Flipper length (mm)",
y = "Body mass (g)",
color = "Penguin species",
shape = "Penguin species") +
theme(legend.position = c(0.2, 0.7),
legend.background =
element_rect(fill = "white",
color = NA),
plot.title.position = "plot",
plot.caption =
element_text(hjust = 0,
face= "italic"),
plot.caption.position = "plot")
```
````
```{r penguinimage, fig.cap = "Flipper length and body mass for Adelie, Chinstrap and Gentoo Penguins.", out.width = "100%"}
if(! "palmerpenguins" %in% installed.packages()) {
install.packages("palmerpenguins", repo = "https://cran.rstudio.com/")
}
if(! "ggplot2" %in% installed.packages()) {
install.packages("ggplot2", repo = "https://cran.rstudio.com/")
}
library(palmerpenguins); library(ggplot2)
ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g)) +
geom_point(aes(color = species,
shape = species),
size = 3,
alpha = 0.8) +
theme_minimal() +
scale_color_manual(values = c("darkorange","purple","cyan4")) +
labs(title = "Penguin size, Palmer Station LTER",
x = "Flipper length (mm)",
y = "Body mass (g)",
color = "Penguin species",
shape = "Penguin species") +
theme(legend.position = c(0.2, 0.7),
legend.background = element_rect(fill = "white", color = NA),
plot.title.position = "plot",
plot.caption = element_text(hjust = 0, face= "italic"),
plot.caption.position = "plot")
```
You can also use---in `doctype: jou` documents---the `\begin{figure*}` environment of LaTeX to insert already-generated images across both columns; the code for this follows, but an additional image is only generated for `doctype: jou`. (Note that including images in the traditional R Markdown way---with code like ``---will work as well, but will not span two columns.)
```{r, results = "asis"}
# by setting `results="asis"`, this is interpreted as LaTeX code
if(rmarkdown::yaml_front_matter("example.Rmd")$doctype == "jou") {
cat("\`\`\`\n\\begin{figure*}\n\\centering\n\\includegraphics{example_files/figure-latex/\npenguinimage.pdf}\n\\caption{Caption for image.}\n\\end{figure*}\n\`\`\`\n")
cat("\\begin{figure*}\n\\centering\n\\includegraphics{example_files/figure-latex/penguinimage.pdf}\n\\caption{When included as an external file, images can be placed in \\textbackslash{}begin\\{figure*\\} environments \\textbackslash{}end{figure*}; these will be placed where appropriate, but will by default take up the full \\textbackslash{}textwidth.}\n\\end{figure*}")
} else {
cat(paste0("\`\`\`
\\begin{figure*}
\\centering
\\includegraphics{example_files/figure-latex/penguinimage.pdf}
\\caption{Caption for image.}
\\end{figure*}
\`\`\`"), collapse = "\n")
}
```
## Multiple figures
You can even include multiple figures concurrently in one section using some tricks of R Markdown [as described here](https://bookdown.org/yihui/rmarkdown-cookbook/latex-subfigure.html#latex-subfigure); this is why it calls `extra_dependencies: "subfig"` in the YAML at the top. However, again, this will look relatively strange in `doctype: jou`, given that the images will not by default span both columns.
```{r morepenguins, fig.cap = 'Different ways of looking at penguin bills. Note that this sort of multiple-figure-in-one-section plot will look best in doctypes man, doc, and stu -- and be a bit abbreviated in doctype jou.', fig.subcap=c('Penguin bill length negatively correlates with penguin bill depth', 'Penguin bill length positively correlates with body mass', 'Boxplot of penguin bill lengths by species'), fig.ncol = 2, out.width = "50%", fig.align = "center"}
plot(penguins$bill_length_mm, penguins$bill_depth_mm)
plot(penguins$bill_length_mm, penguins$body_mass_g)
boxplot(penguins$bill_length_mm ~ penguins$species)
```
# Including tables
There are many great R packages for writing LaTeX tables in R; I won't cover them extensively here, but they include {_kableExtra_}, {_xtable_}, {_[gt](https://gt.rstudio.com/index.html)_}, {_[gtsummary](https://www.danieldsjoberg.com/gtsummary/)_}, and {_stargazer_}. Most of them don't automatically format their contents in APA style. This is one of the places where {_[papja](https://github.com/crsh/papaja)_}, mentioned above, can be helpful; the R functions do indeed have some intentional formatting like `papaja::apa_table()` which will automatically format things _for LaTeX and in APA style_. See the document `tables_ex.Rmd` for more.
A simple example table is included here using the `knitr::kable()` function. Including the `caption` argument is required for the LaTeX {_apa7_} package to recognize it as a table and mark it with the heading "Table 1."
```
library(dplyr)
penguins %>%
group_by(island, species) %>%
summarize(
n = n(),
meanlength = mean(
flipper_length_mm,
na.rm = TRUE),
sd = sd(flipper_length_mm,
na.rm = TRUE),
.groups = "drop"
) %>%
knitr::kable(format = "latex",
booktabs = TRUE,
escape = FALSE,
longtable = FALSE,
digits = 2,
col.names = c("Island",
"Species", "\\textit{n}",
"Flipper length (\\textit{M})",
"(\\textit{SD})"),
align = c("l", "l", "c", "c", "c"),
caption = "Summary of flipper lengths
across species and islands.")
```
```{r}
if(! "dplyr" %in% installed.packages()) {
install.packages("dplyr", repo = "https://cran.rstudio.com/")
}
library(dplyr)
penguins %>%
group_by(island, species) %>%
summarize(
n = n(),
meanlength = mean(flipper_length_mm, na.rm = TRUE),
sd = sd(flipper_length_mm, na.rm = TRUE),
.groups = "drop"
) %>%
knitr::kable(format = "latex",
booktabs = TRUE,
escape = FALSE,
longtable = FALSE,
digits = 2,
col.names = c("Island", "Species", "\\textit{n}",
"Flipper length (\\textit{M})", "(\\textit{SD})"),
align = c("l", "l", "c", "c", "c"),
caption = "Summary of flipper lengths across species and islands.")
```
# More information
The reader hoping for more information should review some of the following books:
* [R Markdown: The Definitive Guide](https://bookdown.org/yihui/rmarkdown/) by Yihui Xie, J. J. Allaire, Garrett Grolemund
* [R Markdown Cookbook](https://bookdown.org/yihui/rmarkdown-cookbook/) by Yihui Xie, Christophe Dervieux, & Emily Riederer
* [bookdown: Authoring Books and Technical Documents with R Markdown](https://bookdown.org/yihui/bookdown/) by Yihui Xie
# Wrapping up
You needn't write anything below the title of your references section---the bibliography will be automatically generated. If you notice that something is inappropriately not capitalized, make sure it is capitalized correctly in your .bib file; if it is, consider surrounding it with curly brackets to ensure the correct formatting.
# References