R Markdown Cookbook
R Markdown Cookbook
R Markdown Cookbook
To the most amazing cooks in my life, Xie Shaobai and Si Zhinan.
—Yihui
List of Tables xv
Preface xix
1 Installation 1
1.1 Use a Pandoc version not bundled with the RStudio IDE . 1
1.2 Install LaTeX (TinyTeX) for PDF reports . . . . . . . . . . 1
1.3 Install missing LaTeX packages . . . . . . . . . . . . . . 1
2 Conceptual Overview 3
2.1 What happens when we render? . . . . . . . . . . . . . . 3
2.2 R Markdown anatomy . . . . . . . . . . . . . . . . . . . 3
2.2.1 YAML metadata . . . . . . . . . . . . . . . . . . . 3
2.2.2 Narrative . . . . . . . . . . . . . . . . . . . . . . 3
2.2.3 Code chunks . . . . . . . . . . . . . . . . . . . . 4
2.2.4 Document body . . . . . . . . . . . . . . . . . . . 4
2.3 What can we change to change the results? . . . . . . . . 4
3 Basics 5
3.1 Code chunks and inline R code . . . . . . . . . . . . . . . 5
3.2 Write Markdown in the RStudio visual editor . . . . . . . 5
3.3 Render an R script to a report . . . . . . . . . . . . . . . 5
3.4 Convert R Markdown to R script . . . . . . . . . . . . . . 6
3.5 R Markdown Notebooks . . . . . . . . . . . . . . . . . . 6
4 Document Elements 7
4.1 Insert page breaks . . . . . . . . . . . . . . . . . . . . . 7
4.2 Set the document title dynamically . . . . . . . . . . . . . 7
vii
viii Contents
5 Formatting 13
5.1 Font color . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.1.1 Using an R function to write raw HTML or LaTeX
code . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.1.2 Using a Pandoc Lua filter (*) . . . . . . . . . . . . 13
5.2 Indent text . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.3 Control the width of text output . . . . . . . . . . . . . . 14
5.4 Control the size of plots/images . . . . . . . . . . . . . . 14
5.5 Figure alignment . . . . . . . . . . . . . . . . . . . . . . 14
5.6 Verbatim code chunks . . . . . . . . . . . . . . . . . . . 14
5.6.1 Show a verbatim inline expression . . . . . . . . . 14
5.7 Line numbers for code blocks (*) . . . . . . . . . . . . . . 15
5.8 Multi-column layout (*) . . . . . . . . . . . . . . . . . . . 15
Contents ix
6 LaTeX Output 17
6.1 Add LaTeX code to the preamble . . . . . . . . . . . . . . 17
6.2 Pandoc options for LaTeX output . . . . . . . . . . . . . 17
6.3 Add logo to title page . . . . . . . . . . . . . . . . . . . . 17
6.4 Include additional LaTeX packages . . . . . . . . . . . . 18
6.4.1 Loading LaTeX packages . . . . . . . . . . . . . . 18
6.4.2 Example packages . . . . . . . . . . . . . . . . . 18
6.5 Control the placement of figures . . . . . . . . . . . . . . 18
6.5.1 Floating environments . . . . . . . . . . . . . . . 18
6.5.2 Prevent figures from floating . . . . . . . . . . . . 18
6.5.3 Force floats forward . . . . . . . . . . . . . . . . 18
6.5.4 Adjust LaTeX placement rules (*) . . . . . . . . . . 19
6.6 LaTeX sub-figures . . . . . . . . . . . . . . . . . . . . . 19
6.7 Render documents containing Unicode characters . . . . 19
6.8 Generate a LaTeX fragment . . . . . . . . . . . . . . . . 19
6.9 Add custom headers and footers (*) . . . . . . . . . . . . 19
6.10 Use a custom Pandoc LaTeX template (*) . . . . . . . . . 20
6.11 Write raw LaTeX code . . . . . . . . . . . . . . . . . . . 20
6.12 For hardcore LaTeX users (*) . . . . . . . . . . . . . . . . 20
7 HTML Output 21
7.1 Apply custom CSS . . . . . . . . . . . . . . . . . . . . . 21
7.2 Center section headings . . . . . . . . . . . . . . . . . . 21
7.3 Style code blocks and text output . . . . . . . . . . . . . . 21
7.4 Scrollable code blocks (*) . . . . . . . . . . . . . . . . . . 21
7.5 Fold all code blocks but show some initially . . . . . . . . 22
7.6 Put content in tabs . . . . . . . . . . . . . . . . . . . . . 22
7.7 Embed the Rmd source file in the HTML output file . . . . 22
7.8 Embed arbitrary files in the HTML output file . . . . . . . 22
7.9 Use a custom HTML template (*) . . . . . . . . . . . . . . 22
7.10 Include the content of an existing HTML file (*) . . . . . . 23
7.11 Add a custom browser icon . . . . . . . . . . . . . . . . . 23
7.12 Use the <details> disclosure element . . . . . . . . . . . 23
7.13 Sharing HTML output on the web . . . . . . . . . . . . . 23
7.13.1 R-specific services . . . . . . . . . . . . . . . . . 23
7.13.2 Static website services . . . . . . . . . . . . . . . 23
7.14 Improve accessibility of HTML pages . . . . . . . . . . . 24
7.15 For hardcore HTML users (*) . . . . . . . . . . . . . . . . 24
8 Word 25
x Contents
10 Tables 29
10.1 The function knitr::kable() . . . . . . . . . . . . . . . 29
10.1.1 Supported table formats . . . . . . . . . . . . . . 29
10.1.2 Change column names . . . . . . . . . . . . . . . 29
10.1.3 Specify column alignment . . . . . . . . . . . . . 29
10.1.4 Add a table caption . . . . . . . . . . . . . . . . . 29
10.1.5 Format numeric columns . . . . . . . . . . . . . . 30
10.1.6 Display missing values . . . . . . . . . . . . . . . 30
10.1.7 Escape special characters . . . . . . . . . . . . . . 30
10.1.8 Multiple tables side by side . . . . . . . . . . . . . 30
10.1.9 Generate multiple tables from a for-loop (*) . . . . 30
10.1.10 Customize LaTeX tables (*) . . . . . . . . . . . . . 30
10.1.11 Customize HTML tables (*) . . . . . . . . . . . . . 30
10.2 The kableExtra package . . . . . . . . . . . . . . . . . . 31
10.2.1 Set the font size . . . . . . . . . . . . . . . . . . . 31
10.2.2 Style specific rows/columns . . . . . . . . . . . . 31
10.2.3 Group rows/columns . . . . . . . . . . . . . . . . 31
10.2.4 Scaling down wide tables in LaTeX . . . . . . . . . 31
10.3 Other packages for creating tables . . . . . . . . . . . . . 31
11 Chunk Options 33
11.1 Use variables in chunk options . . . . . . . . . . . . . . . 33
11.2 Do not stop on error . . . . . . . . . . . . . . . . . . . . 33
11.3 Multiple graphical output formats for the same plot . . . . 33
11.4 Cache time-consuming code chunks . . . . . . . . . . . . 33
Contents xi
15 Other Languages 45
15.1 Register a custom language engine (*) . . . . . . . . . . . 45
15.2 Run Python code and interact with Python . . . . . . . . 45
15.3 Execute content conditionally via the asis engine . . . . . 45
15.4 Execute Shell scripts . . . . . . . . . . . . . . . . . . . . 45
15.5 Visualization with D3 . . . . . . . . . . . . . . . . . . . . 46
15.6 Write the chunk content to a file via the cat engine . . . . 46
15.6.1 Write to a CSS file . . . . . . . . . . . . . . . . . 46
15.6.2 Include LaTeX code in the preamble . . . . . . . . 46
15.6.3 Write YAML data to a file and also display it . . . . 46
15.7 Run SAS code . . . . . . . . . . . . . . . . . . . . . . . . 46
15.8 Run Stata code . . . . . . . . . . . . . . . . . . . . . . . 47
15.9 Create graphics with Asymptote . . . . . . . . . . . . . . 47
15.9.1 Generate data in R and read it in Asymptote . . . . 47
15.10 Style HTML pages with Sass/SCSS . . . . . . . . . . . . . 47
16 Managing Projects 49
16.1 Source external R scripts . . . . . . . . . . . . . . . . . . 49
16.2 Read external scripts into a chunk . . . . . . . . . . . . . 49
16.3 Read multiple code chunks from an external script (*) . . . 49
16.4 Child documents (*) . . . . . . . . . . . . . . . . . . . . 49
16.5 Keep the plot files . . . . . . . . . . . . . . . . . . . . . . 50
16.6 The working directory for R code chunks . . . . . . . . . 50
16.7 R package vignettes . . . . . . . . . . . . . . . . . . . . . 50
16.8 R Markdown templates in R packages . . . . . . . . . . . 50
16.8.1 Template use-cases . . . . . . . . . . . . . . . . . 51
16.8.2 Template setup . . . . . . . . . . . . . . . . . . . 51
16.9 Write books and long-form reports with bookdown . . . . 51
16.10 Build websites with blogdown . . . . . . . . . . . . . . . 51
17 Workflow 53
17.1 Use RStudio keyboard shortcuts . . . . . . . . . . . . . . 53
Contents xiii
xv
List of Figures
xvii
xviii List of Figures
xix
xx Preface
to the knitr package (?) (note that R Markdown is only one of the docu-
ment formats that knitr supports). If you want to read a shorter version,
you may find Karl Broman’s minimal tutorial “knitr in a knutshell”6 help-
ful.
• bookdown: Authoring Books and Technical Documents with R Markdown (?) is
a short book as the official documentation of the bookdown package (?),
which is designed to simplify the creation of long-format documents in
R Markdown.
• blogdown: Creating Websites with R Markdown (?) introduces how to create
websites in R Markdown with the blogdown package (?).
Where relevant, this book provides references to these existing resources. By
the way, the official R Markdown website also contains a lot of resources that
you may find helpful: https://rmarkdown.rstudio.com.
You do not need to read this book in a particular order. Later chapters are
not necessarily more challenging than previous chapters. The chapters and
sections that we consider to be more advanced than others are marked with
an asterisk (*) in their titles. It may be most efficient to read this book when
you have some specific tasks in mind that you want to do with R Markdown,
otherwise you can thumb through the table of contents and see if you are
interested in any particular parts. We have tried to make each section and
example as self-contained as possible, so you do not have to go back and forth
among different parts of this book. In some cases, cross-referencing is un-
avoidable, and we will refer you to the background knowledge required to
understand a certain example.
If you want to try the examples by yourself, the full source code of this
book and examples are freely provided on GitHub at https://github.com/
yihui/rmarkdown-cookbook. If you are reading the electronic version of this
book, you may also just copy and paste the examples from the pages and run
them in your favorite editor.
6
https://kbroman.org/knitr_knutshell/
xxii Preface
xfun::session_info(c(
'bookdown', 'knitr', 'rmarkdown', 'xfun'
), dependencies = FALSE)
We do not add prompts (> and +) to R source code in this book, and we
comment out the text output with two hashes ## by default, as you can
see from the R session information above. This is for your convenience
when you want to copy and run the code (the text output will be ignored
since it is commented out). Package names are in bold text (e.g., rmark-
down), and inline code and filenames are formatted in a typewriter font
(e.g., knitr::knit('foo.Rmd')). Function names are followed by parenthe-
ses (e.g., blogdown::serve_site()). The double-colon operator :: means ac-
cessing an object from a package.
“Rmd” is the filename extension of R Markdown files, and also an abbrevia-
tion of R Markdown in this book.
Acknowledgments
As usual, first I want to thank my employer RStudio for giving me the free-
dom to work on this book. Since I started working on it, my weekly meet-
ing time with my manager, Tareef Kawaf, was first reduced from 15 minutes
to 5 minutes, and then the meetings were just canceled. I have heard from
several friends that they have too many unbearable meetings in their institu-
xxiv Preface
tions, which waste a lot of their time. In terms of managing distractions, one
of them recently lamented, “You may be able to mute Slack for five minutes,
but can you possibly mute it for a whole day?” “Of course, I can!” I told her. I
can probably mute it for a whole month if I like. Do not get me wrong—I do
not mean Tareef or my colleagues are distractions. I only mean how much
freedom they can offer me.
I came up with the idea of writing this cookbook after I published the R Mark-
down Definitive Guide, but ideas are often cheap. It is the execution that is
hard and expensive. If it were not for Michael Harper’s7 initial pushing, I
would never have started working on it seriously. Christophe Dervieux has
always been around whenever I need help. He used his R and R Markdown
skills to build a dashboard (with the flexdashboard package) to guide me
to the potentially interesting and useful topics to write on. Meanwhile, he
has also helped me in numerous other GitHub issues, so I could have more
time for writing the book, instead of spending whole days on wrestling with
bug reports that do not have minimal reproducible examples attached. Sim-
ilarly, several people have been helping with answering R Markdown ques-
tions on Stack Overflow, including Martin Schmelzer, Marcel Schilling, and
Ralf Stubner. Perhaps it was not their intention to save me time, but their ef-
fort did save me a lot of time. Recently, Johannes Friedrich also came to my
attention on Stack Overflow, after a few times when I opened a new Stack
Overflow question only to find it already answered by him.
David Keyes saved my life in Section 10.3, since he had written a wonder-
ful blog post8 to introduce several R packages to create tables, with which I
was not very familiar. Other online materials that have helped me a lot in-
clude Holtz Yan’s post on some R Markdown tips,9 Nicholas Tierney’s book
R Markdown for Scientists10 , Maëlle Salmon’s R Markdown course,11 Jennifer
Thompson’s R Markdown course,12 Emi Tanaka’s R Markdown workshop,13
Alison Hill’s R Markdown workshop14 (co-taught with me), and Alison Hill
and Emi Tanaka’s R Markdown workshop.15
Many people have made contributions in the GitHub repository of this
7
http://mikeyharper.uk
8
https://rfortherestofus.com/2019/11/how-to-make-beautiful-tables-in-r/
9
https://holtzy.github.io/Pimp-my-rmd/
10
https://rmd4sci.njtierney.com
11
https://github.com/maelle/rmd_course_isglobal
12
https://github.com/jenniferthompson/RepResearchRMarkdown
13
https://github.com/emitanaka/combine2019
14
https://arm.rbind.io
15
https://ysc-rmarkdown.netlify.app
Preface xxv
all these reviewers for their helpful feedback, including Carl Boettiger, John
Blischak, Sharla Gelfand, Johannes Friedrich, Atsushi Yasumoto, and other
anonymous reviewers.
I worked on the last part of this book in the vacant house (without Internet!)
of my good old neighbors, Dong Guo and Qian Jia, after they moved to an-
other city. I’m grateful to them for letting me use their house as my tempo-
rary office to finish up the book when I felt rather exhausted and needed a
quiet environment. It was sad to say goodbye to them. To me, this book, fin-
ished in their house, will also be associated with some of my fond memories
of this family, including their parents and lovely little daughter.
Lastly, I will definitely not miss this unique opportunity to thank my two
little “super helpful co-workers” (5 and 3) at home during the COVID-19 pan-
demic, without whom I could have published this book five months earlier.
Now I miss the teachers at their daycare center (Small Miracle) and feel day-
care centers are perhaps not that expensive…
Yihui Xie
Elkhorn, Nebraska
About the Authors
Yihui typed out most of the words in this book, which is the only justification
for him being the “first” author. Christophe has made substantial contribu-
tion to this book by helping Yihui organize all the GitHub issues and occa-
sionally writing a few sections. Emily was originally a reviewer of this book.
Since Yihui was not patient enough to deal with her lengthy comments, he
invited her to become a co-author of this book (out of revenge) to feel his
pain of having to deal with so many additional things when he thought he
was pretty much done! Just kidding… No, he invited her out of full apprecia-
tion, because her comments were so helpful, yet Yihui lacked the time to do
all the improvements that she suggested.
When you see the pronoun “I” in this book, it refers to Yihui. Using “I” instead
of “We” does not mean the co-authors were forgotten, but Yihui wanted to
express certain opinions completely on his own. He certainly wants to ap-
pear smart, but in case he is actually silly, he wants to be silly alone.
Yihui Xie
Yihui Xie (https://yihui.org) is a software engineer at RStudio (https:
//www.rstudio.com). He earned his PhD from the Department of Statis-
tics, Iowa State University. He is interested in interactive statistical graph-
ics and statistical computing. As an active R user, he has authored several
R packages, such as knitr, bookdown, blogdown, xaringan, tinytex, roll-
down, animation, DT, tufte, formatR, fun, xfun, testit, mime, highr, servr,
and Rd2roxygen, among which the animation package won the 2009 John
M. Chambers Statistical Software Award (ASA). He also co-authored a few
other R packages, including shiny, rmarkdown, pagedown, and leaflet.
He has authored two books, Dynamic Documents with knitr (?), and bookdown:
Authoring Books and Technical Documents with R Markdown (?), and co-authored
xxvii
xxviii About the Authors
two books, blogdown: Creating Websites with R Markdown (?), and R Markdown:
The Definitive Guide (?).
In 2006, he founded the Capital of Statistics (https://cosx.org), which has
grown into a large online community on statistics in China. He initiated the
Chinese R conference in 2008, and has been involved in organizing R con-
ferences in China since then. During his PhD training at Iowa State Univer-
sity, he won the Vince Sposito Statistical Computing Award (2011) and the
Snedecor Award (2012) in the Department of Statistics.
He usually reads Twitter messages once a week (https://twitter.com/
xieyihui), and most of the time you can find him on GitHub (https://
github.com/yihui).
He has four hobbies: reading, writing (mostly blogging), cooking, and play-
ing badminton. He is actually more interested in cooking than eating. There
are not many types of food that he cannot resist eating, and spicy food is one
of the few. Since cooking is more fun, he rarely goes to restaurants. When he
does go and is asked “how spicy you want your food to be” in the restaurant,
he usually answers “as spicy as your chef can make it to be.”
Christophe Dervieux
Christophe Dervieux is an active member of the R community, currently liv-
ing in France. With a master’s degree in energy and economics, he started
working with R as an analyst doing economic studies about market designs,
before becoming a developer advocate and R admin, promoting R and sup-
porting R users where he works.
He is interested in helping others get the most from R, and you can find him
wandering in the RStudio Community as a sustainer, or on several GitHub
issue boards for various R packages. In both places, you may better recognize
him by his shorter handle “cderv.”
As an R developer, he is a contributor to several R packages, such as book-
down, rmarkdown, and knitr. He has also co-authored the crrri package.
His own projects can be found on GitHub (https://github.com/cderv),
and sometimes he shares his ideas on Twitter (https://twitter.com/
chrisderv).
About the Authors xxix
He does not like spicy food, but he enjoys playing badminton every week.
Emily Riederer
Emily Riederer works in data science for the consumer finance industry
where she leads a team to build analysis tools in R and cultivate an open sci-
ence culture in industry. Previously, she studied mathematics and statistics
at the University of North Carolina at Chapel Hill.
Emily frequently discusses R on Twitter (https://twitter.com/
emilyriederer) and in her blog (https://emily.rbind.io) and
shared projects, including her projmgr R package, on GitHub
(https://github.com/emilyriederer). She has also served as a pack-
age reviewer for rOpenSci and a founding co-organizer of the annual
satRday Chicago R conference.
Emily’s other interests include reading and weightlifting. She thinks she
likes spicy food, but since she has only ever lived in the United States, she
has been told that she does not really know what that actually means.
1
Installation
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
1.1 Use a Pandoc version not bundled with the RStudio IDE
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
1
2
Conceptual Overview
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
2.2.2 Narrative
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
3
4 2 Conceptual Overview
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
5
6 3 Basics
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
7
8 4 Document Elements
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
13
14 5 Formatting
FIGURE 5.3: A two-column layout that works for HTML, LaTeX, and Beamer
output.
6
LaTeX Output
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
17
18 6 LaTeX Output
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
21
22 7 HTML Output
7.7 Embed the Rmd source file in the HTML output file
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
25
26 8 Word
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
27
28 9 Multiple Output Formats
9.6.1 Syntax
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
29
30 10 Tables
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
33
34 11 Chunk Options
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
37
38 12 Output Hooks (*)
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
39
40 13 Chunk Hooks (*)
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
41
42 14 Miscellaneous knitr Tricks
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
45
46 15 Other Languages
15.6 Write the chunk content to a file via the cat engine
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
49
50 16 Managing Projects
FIGURE 16.1: Change the default working directory for all R Markdown doc-
uments in RStudio.
FIGURE 16.2: Knit an Rmd document with other possible working directo-
ries in RStudio.
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
53
54 17 Workflow
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
18.1.4 Cache
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
55
56 18 knitr’s Chunk and Package Options
18.1.5 Plots
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
18.1.6 Animation
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.