0% found this document useful (0 votes)
538 views87 pages

R Markdown Cookbook

Uploaded by

Alex Palacios
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
538 views87 pages

R Markdown Cookbook

Uploaded by

Alex Palacios
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Yihui Xie, Christophe Dervieux, Emily Riederer

R Markdown Cookbook
To the most amazing cooks in my life, Xie Shaobai and Si Zhinan.
—Yihui

To my supporting wife, Caroline, and our lovely newborn, Axel.


—Christophe

To my mom, who taught me the joy of life-long learning.


—Emily
Contents

List of Tables xv

List of Figures xvii

Preface xix

About the Authors xxvii

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

4.3 Access the document metadata in R code . . . . . . . . . 7


4.4 Unnumbered sections . . . . . . . . . . . . . . . . . . . 7
4.5 Bibliographies and citations . . . . . . . . . . . . . . . . 8
4.5.1 Changing citation style . . . . . . . . . . . . . . . 8
4.5.2 Add an item to a bibliography without using it . . . 8
4.5.3 Add all items to the bibliography . . . . . . . . . . 8
4.5.4 Include appendix after bibliography (*) . . . . . . 8
4.6 Generate R package citations . . . . . . . . . . . . . . . . 8
4.7 Cross-referencing within documents . . . . . . . . . . . 8
4.8 Update the date automatically . . . . . . . . . . . . . . . 9
4.9 Multiple authors in a document . . . . . . . . . . . . . . 9
4.10 Numbered figure captions . . . . . . . . . . . . . . . . . 9
4.11 Combine words into a comma-separated phrase . . . . . 9
4.12 Preserve a large number of line breaks . . . . . . . . . . . 10
4.13 Convert models to equations . . . . . . . . . . . . . . . . 10
4.14 Create an animation from multiple R plots . . . . . . . . 10
4.15 Create diagrams . . . . . . . . . . . . . . . . . . . . . . 10
4.15.1 Basic diagrams . . . . . . . . . . . . . . . . . . . 10
4.15.2 Adding parameters to plots . . . . . . . . . . . . . 11
4.15.3 Other packages for making diagrams . . . . . . . 11
4.16 Escape special characters . . . . . . . . . . . . . . . . . . 11
4.17 Comment out text . . . . . . . . . . . . . . . . . . . . . 11
4.18 Omit a heading in the table of contents . . . . . . . . . . 11
4.19 Put together all code in the appendix (*) . . . . . . . . . . 12
4.20 Manipulate Markdown via Pandoc Lua filters (*) . . . . . 12

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

8.1 Custom Word templates . . . . . . . . . . . . . . . . . . 25


8.2 The two-way workflow between R Markdown and Word . 25
8.3 Style individual elements . . . . . . . . . . . . . . . . . . 26

9 Multiple Output Formats 27


9.1 LaTeX or HTML output . . . . . . . . . . . . . . . . . . . 27
9.2 Display HTML widgets . . . . . . . . . . . . . . . . . . . 27
9.3 Embed a web page . . . . . . . . . . . . . . . . . . . . . 27
9.4 Multiple figures side by side . . . . . . . . . . . . . . . . 28
9.5 Write raw content (*) . . . . . . . . . . . . . . . . . . . . 28
9.6 Custom blocks (*) . . . . . . . . . . . . . . . . . . . . . . 28
9.6.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . 28
9.6.2 Adding a shaded box . . . . . . . . . . . . . . . . 28
9.6.3 Including icons . . . . . . . . . . . . . . . . . . . 28

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

11.5 Cache a code chunk for multiple output formats . . . . . . 34


11.6 Cache large objects . . . . . . . . . . . . . . . . . . . . . 34
11.7 Hide code, text output, messages, or plots . . . . . . . . . 34
11.8 Hide everything from a chunk . . . . . . . . . . . . . . . 34
11.9 Collapse text output blocks into source blocks . . . . . . . 34
11.10 Reformat R source code . . . . . . . . . . . . . . . . . . 35
11.11 Output text as raw Markdown content (*) . . . . . . . . . 35
11.12 Remove leading hashes in text output . . . . . . . . . . . 35
11.13 Add attributes to text output blocks (*) . . . . . . . . . . . 35
11.14 Post-process plots (*) . . . . . . . . . . . . . . . . . . . . 35
11.15 High-quality graphics (*) . . . . . . . . . . . . . . . . . . 36
11.16 Step-by-step plots with low-level plotting functions (*) . . 36
11.17 Customize the printing of objects in chunks (*) . . . . . . 36
11.18 Option hooks (*) . . . . . . . . . . . . . . . . . . . . . . 36

12 Output Hooks (*) 37


12.1 Redact source code . . . . . . . . . . . . . . . . . . . . . 37
12.2 Add line numbers to source code . . . . . . . . . . . . . . 37
12.3 Scrollable text output . . . . . . . . . . . . . . . . . . . . 37
12.4 Truncate text output . . . . . . . . . . . . . . . . . . . . 37
12.5 Output figures in the HTML5 format . . . . . . . . . . . . 38

13 Chunk Hooks (*) 39


13.1 Crop plots . . . . . . . . . . . . . . . . . . . . . . . . . . 39
13.2 Optimize PNG plots . . . . . . . . . . . . . . . . . . . . 39
13.3 Report how much time each chunk takes to run . . . . . . 39
13.4 Show the chunk header in the output . . . . . . . . . . . 40
13.5 Embed an interactive 3D plot with rgl . . . . . . . . . . . 40

14 Miscellaneous knitr Tricks 41


14.1 Reuse code chunks . . . . . . . . . . . . . . . . . . . . . 41
14.1.1 Embed one chunk in another chunk (*) . . . . . . 41
14.1.2 Use the same chunk label in another chunk . . . . 41
14.1.3 Use reference labels (*) . . . . . . . . . . . . . . . 41
14.2 Use an object before it is created (*) . . . . . . . . . . . . 41
14.3 Exit knitting early . . . . . . . . . . . . . . . . . . . . . 42
14.4 Generate a plot and display it elsewhere . . . . . . . . . . 42
14.5 Modify a plot in a previous code chunk . . . . . . . . . . . 42
14.6 Save a group of chunk options and reuse them (*) . . . . . 42
14.7 Use knitr::knit_expand() to generate Rmd source . . . 42
xii Contents

14.8 Allow duplicate labels in code chunks (*) . . . . . . . . . . 43


14.9 A more transparent caching mechanism . . . . . . . . . . 43
14.9.1 Invalidate the cache by changing code in the expres-
sion . . . . . . . . . . . . . . . . . . . . . . . . . 43
14.9.2 Invalidate the cache by changes in global variables 43
14.9.3 Keep multiple copies of the cache . . . . . . . . . . 43
14.9.4 Comparison with knitr’s caching . . . . . . . . . . 43

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

17.2 Spell-check R Markdown . . . . . . . . . . . . . . . . . . 53


17.3 Render R Markdown with rmarkdown::render() . . . . . 53
17.4 Parameterized reports . . . . . . . . . . . . . . . . . . . 54
17.5 Customize the Knit button (*) . . . . . . . . . . . . . . . 54
17.6 Collaborate on Rmd documents through Google Drive . . 54
17.7 Organize an R Markdown project into a research website
with workflowr . . . . . . . . . . . . . . . . . . . . . . . 54
17.8 Send emails based on R Markdown . . . . . . . . . . . . 54

18 knitr’s Chunk and Package Options 55


18.1 Chunk options . . . . . . . . . . . . . . . . . . . . . . . 55
18.1.1 Code evaluation . . . . . . . . . . . . . . . . . . . 55
18.1.2 Text output . . . . . . . . . . . . . . . . . . . . . 55
18.1.3 Code decoration . . . . . . . . . . . . . . . . . . 55
18.1.4 Cache . . . . . . . . . . . . . . . . . . . . . . . . 55
18.1.5 Plots . . . . . . . . . . . . . . . . . . . . . . . . . 56
18.1.6 Animation . . . . . . . . . . . . . . . . . . . . . . 56
18.1.7 Code chunk . . . . . . . . . . . . . . . . . . . . . 56
18.1.8 Child documents . . . . . . . . . . . . . . . . . . 56
18.1.9 Language engines . . . . . . . . . . . . . . . . . . 56
18.1.10 Option templates . . . . . . . . . . . . . . . . . . 56
18.1.11 Extracting source code . . . . . . . . . . . . . . . 56
18.1.12 Other chunk options . . . . . . . . . . . . . . . . 56
List of Tables

4.1 Date and time formats in R. . . . . . . . . . . . . . . . . . 9

6.1 Default LaTeX float settings. . . . . . . . . . . . . . . . . 19

10.1 An example table caption. . . . . . . . . . . . . . . . . . . 29


10.2 Two tables placed side by side. . . . . . . . . . . . . . . . 30
10.3 Two tables created by knitr::kables(). . . . . . . . . . . . . 30

17.1 RStudio keyboard shortcuts related to R Markdown. . . . . 53

xv
List of Figures

2.1 A diagram illustrating how an R Markdown document is con-


verted to the final output document. . . . . . . . . . . . . 3
2.2 A flowchart of inputs and outputs to a language engine. . . 4
2.3 A simple R Markdown document illustrated as a set of nested
containers. . . . . . . . . . . . . . . . . . . . . . . . . . 4

3.1 The visual Markdown editor in RStudio. . . . . . . . . . . 5

4.1 Example of cross-referencing within an R Markdown docu-


ment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.2 A Pac-man animation. . . . . . . . . . . . . . . . . . . . . 10
4.3 A diagram showing a programmer’s daydream. . . . . . . 10
4.4 A diagram using parameters input from R. . . . . . . . . . 11

5.1 Normal text output that is too wide. . . . . . . . . . . . . 14


5.2 Text output wrapped with the listings package. . . . . . . 14
5.3 A two-column layout that works for HTML, LaTeX, and
Beamer output. . . . . . . . . . . . . . . . . . . . . . . . 15

6.1 A logo on a LaTeX title page. . . . . . . . . . . . . . . . . 17

7.1 Wrap text output in the details element. . . . . . . . . . . 23

8.1 Find the styles of a specific document element. . . . . . . 25


8.2 Modify the styles of an element in a Word document. . . . 25
8.3 Modify the styles of tables in a Word document. . . . . . . 25

9.1 Embed Yihui’s homepage as an iframe or screenshot. . . . 27


9.2 Side-by-side figures. . . . . . . . . . . . . . . . . . . . . 28

10.1 A striped table created with HTML and CSS. . . . . . . . . 31

11.1 A plot rendered via the tikz device. . . . . . . . . . . . . . 36

xvii
xviii List of Figures

13.1 A plot that is not cropped. . . . . . . . . . . . . . . . . . . 39


13.2 A plot that is cropped. . . . . . . . . . . . . . . . . . . . . 39
13.3 A 3D scatterplot generated from the rgl package. . . . . . . 40

16.1 Change the default working directory for all R Markdown


documents in RStudio. . . . . . . . . . . . . . . . . . . . 50
16.2 Knit an Rmd document with other possible working directo-
ries in RStudio. . . . . . . . . . . . . . . . . . . . . . . . 50
16.3 Autocomplete file paths in an Rmd document in RStudio. . 50
Preface

R Markdown is a powerful tool for combining analysis and reporting into


the same document. Since the birth of the rmarkdown package (?) in early
2014, R Markdown has grown substantially from a package that supports a
few output formats, to an extensive and diverse ecosystem that supports the
creation of books, blogs, scientific articles, websites, and even resumes.
There is a wealth of guidance that has been written over the past few years,
and the book R Markdown: The Definitive Guide1 (?) provides a detailed refer-
ence on the built-in R Markdown output formats of the rmarkdown pack-
age, as well as several other extension packages. However, we have received
comments from our readers and publisher that it would be beneficial to pro-
vide more practical and relatively short examples to show the interesting and
useful usage of R Markdown, because it can be daunting to find out how to
achieve a certain task from the aforementioned reference book (put another
way, that book is too dry to read). As a result, this cookbook was born.
Despite the existence of the official documentation, R Markdown users of-
ten seek help on Stack Overflow, a popular Q&A forum. At the time of writ-
ing, there are more than 6,000 questions with the r-markdown tag.2 This
huge number means that the use of the forum can be difficult if you do not
have a specific problem to search for. Therefore, it may be hard for you to
realize all possible things that you could do with R Markdown or how to do
them. This book aims to draw together popular posts from Stack Overflow
and other online resources (such as blog posts or tutorials) to provide up-to-
date solutions for everyday queries that users commonly make. In fact, to
help us make decisions on the potential topics to cover in this book, the sec-
ond author of this book, Christophe, has built an R Markdown dashboard to
scrape Stack Overflow daily for the most popular posts. Hopefully, our cook-
book can become more useful by including recipes from these popular posts.
This book is designed to provide a range of examples on how to extend the
1
https://bookdown.org/yihui/rmarkdown/
2
https://stackoverflow.com/questions/tagged/r-markdown

xix
xx Preface

functionality of your R Markdown documents. As a cookbook, this guide is


recommended to new and intermediate R Markdown users who desire to
enhance the efficiency of using R Markdown and also explore the power of
R Markdown.

How to read this book


It is recommended that readers have a basic understanding of R Markdown.
Chapter 23 of R Markdown: The Definitive Guide (?) provides an overview of
the basics of R Markdown and is recommended background reading for any
new users of R Markdown. For example, we did not cover Markdown syntax
in this book, and expect readers to learn Markdown elsewhere. In particular,
we strongly recommend that you go through the full manual of Pandoc4 at
least once. The manual is quite lengthy, but it is also a gold mine. You do not
have to remember everything, but it will be very helpful if you are aware of
the possible features of Markdown. For countless times, I have seen5 people
fail to write verbatim code blocks that contain three backticks, or list items
that contain child elements. Without fully reading the Markdown syntax in
the manual, perhaps you will never know or understand the rule “N + 1
outer backticks for N inner backticks” or “indent properly to indicate child
elements.”
We do not intend to provide a full technical reference for R Markdown in
this cookbook. This cookbook aims to supplement, instead of replace, the ex-
isting literature. Therefore, readers may explore the following books if they
want to seek further information:
• R Markdown: The Definitive Guide (?), the technical reference for all R Mark-
down output formats in the rmarkdown package and several other ex-
tension packages.
• Part V (“Communicate”) of R for Data Science (?). This part is less technical
than the above “Definitive Guide,” and hence may be a gentler introduc-
tion to R Markdown.
• Dynamic Documents with R and knitr (?) provides a thorough introduction
3
https://bookdown.org/yihui/rmarkdown/basics.html
4
https://pandoc.org/MANUAL.html
5
https://yihui.org/en/2018/11/hard-markdown/
Preface xxi

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

Structure of the book


The book is broken down into small “recipes” that aim to demonstrate a sin-
gle concept at a time. Chapter 1 provides instructions on how to install the
necessary software tools. Chapter 2 gives a conceptual overview of R Mark-
down. Chapter 3 introduces the basic components of R Markdown, and how
to convert between R Markdown documents and R scripts. Chapter 4 tells
you how to generate certain document elements, such as page breaks, bibli-
ographies, numbered figures, animations, diagrams, etc. Chapter 5 shows
how to format content, such as adjusting the figure size and alignment.
Chapter 6 introduces tips and tricks for those who only want LaTeX/PDF out-
put. Similarly, Chapter 7 is for HTML users, and Chapter 8 is for Word users.
If you want to produce output documents in multiple output formats (which
is often tricky), you may find Chapter 9 useful. Chapter 10 is, to be honest,
my least favorite chapter, but I know a lot of users really want to learn how
to produce tables. I’m not an expert on fancy tables, but hope you will at least
find the list of packages there helpful. Chapter 11 shows some applications
of knitr’s chunk options that you may not know. Chapter 12 and Chapter 13
are a little advanced, but should also be very useful because they show you
the great power of being able to control knitr’s output and behavior with cus-
tom hook functions. Chapter 14 introduces a variety of knitr tricks. Chapter
15 shows examples of using other languages in R Markdown, so you know R
Markdown is not only for R. It also teaches you how to make knitr work with
a new language that has not been supported yet. Chapter 16 introduces tips
on managing projects related to R Markdown. Chapter 17 presents some tips
on enhancing your workflow.
The recipes in this book are usually independent of each other, so you can
pick up any one to read if you do not have a specific goal in mind.

Software information and conventions


The basic R session information when compiling this book is as follows:
Preface xxiii

xfun::session_info(c(
'bookdown', 'knitr', 'rmarkdown', 'xfun'
), dependencies = FALSE)

## R version 4.0.3 (2020-10-10)


## Platform: x86_64-apple-darwin17.0 (64-bit)
## Running under: macOS Big Sur 10.16
##
## Locale: en_US.UTF-8 / en_US.UTF-8 / en_US.UTF-8 / C / en_US.UTF-
8 / en_US.UTF-8
##
## Package version:
## bookdown_0.21.4 knitr_1.30.2 rmarkdown_2.5
## xfun_0.19.3
##
## Pandoc version: 2.11.0.2

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

book by either sending pull requests or filing issues, including Maria


Bekker-Nielsen Dunbar, Nathan Eastwood, Johannes Friedrich, Krishnaku-
mar Gopalakrishnan, Xiangyun Huang, Florian Kohrt, Romain Lesur, Jiax-
iang Li, Song Li, Ulrik Lyngs, Matt Small, Jake Stephen, Atsushi Yasumoto,
Hao Zhu, and John Zobolas. The marvelous cover artwork of this book was
designed by Allison Horst16 and the full cover was finalized by Kevin Craig.
The original idea of this book was partially motivated from a remote talk that
I delivered to the RaukR Summer School in 2018, in which I introduced some
lesser known features of knitr. The audience seemed to like those short in-
troductions of knitr features, which were like recipes. I’d like to thank the
organizers of the summer school, including Marcin Kierczak and Sebastian
Dilorenzo, for inviting me. I have given similar talks later at Genentech and
DahShu.17 I want to thank Michael Lawrence and Yuqing Zhang for the invi-
tations, as well as the audience of these talks, for their feedback. Paul John-
son published a very helpful critique of our book R Markdown: The Definitive
Guide in the journal The American Statistician in 2020. He complained that the
book lacked in-depth examples, therefore the definitive guide was not defini-
tive enough. I truly appreciate and agree with his comments. I hope this new
(cook)book can fill the gap.
This is the fifth book that I have published with my editor John Kimmel. It
has always been a pleasure to work with him and the team at Chapman &
Hall/CRC. I’m excited every time John tells me the new success of bookdown
as it is more widely adopted by other authors. I feel honored to hear from
John that Suzanne Lassandro, the production editor of my previous books,
still tried hard to help with this book even though she has many other re-
sponsibilities and rarely works directly with authors now. Suzanne and our
proofreader (Rebecca Condit) managed to identify “only” 377 issues in our
first draft. Apparently, I was too optimistic when I wondered last time18 if I
would have less than 30 issues in my next book. The LaTeX expert Shashi Ku-
mar helped us fix a thorny LaTeX issue, which was our last obstacle before
the PDF could be printed.
John reached out to several reviewers for their feedback on the manuscript.
Eventually we received nine great reviews. One of them was so great that we
could not help inviting her to co-author this book! It was a lot of work to deal
with the nine reviews, but it was definitely worth the effort. I’d like to thank
16
https://github.com/yihui/rmarkdown-cookbook/issues/180
17
http://dahshu.org
18
https://bookdown.org/yihui/rmarkdown/acknowledgments.html
xxvi Preface

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 Install LaTeX (TinyTeX) for PDF reports


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

1.3 Install missing LaTeX packages


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.1 What happens when we render?


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 2.1: A diagram illustrating how an R Markdown document is con-


verted to the final output document.

2.2 R Markdown anatomy


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

2.2.1 YAML metadata


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

2.2.3 Code chunks


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 2.2: A flowchart of inputs and outputs to a language engine.

2.2.4 Document body


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 2.3: A simple R Markdown document illustrated as a set of nested


containers.

2.3 What can we change to change the results?


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
3
Basics

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

3.1 Code chunks and inline R code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

3.2 Write Markdown in the RStudio visual editor


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 3.1: The visual Markdown editor in RStudio.

3.3 Render an R script to a report


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

3.4 Convert R Markdown to R script


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

3.5 R Markdown Notebooks


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
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.

4.1 Insert page breaks


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.2 Set the document title dynamically


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.3 Access the document metadata in R code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.4 Unnumbered sections


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

4.5 Bibliographies and citations


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.5.1 Changing citation style


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.5.2 Add an item to a bibliography without using it


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.5.3 Add all items to the bibliography


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.5.4 Include appendix after bibliography (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.6 Generate R package citations


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.7 Cross-referencing within documents


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
4.8 Update the date automatically 9

FIGURE 4.1: Example of cross-referencing within an R Markdown docu-


ment.

TABLE 4.1: Date and time formats in R.

4.8 Update the date automatically


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.9 Multiple authors in a document


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.10 Numbered figure captions


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.11 Combine words into a comma-separated phrase


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
10 4 Document Elements

4.12 Preserve a large number of line breaks


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.13 Convert models to equations


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.14 Create an animation from multiple R plots


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 4.2: A Pac-man animation.

4.15 Create diagrams


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.15.1 Basic diagrams


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 4.3: A diagram showing a programmer’s daydream.


4.16 Escape special characters 11

4.15.2 Adding parameters to plots


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 4.4: A diagram using parameters input from R.

4.15.3 Other packages for making diagrams


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.16 Escape special characters


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.17 Comment out text


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.18 Omit a heading in the table of contents


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
12 4 Document Elements

4.19 Put together all code in the appendix (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

4.20 Manipulate Markdown via Pandoc Lua filters (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
5
Formatting

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

5.1 Font color


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

5.1.1 Using an R function to write raw HTML or LaTeX code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

5.1.2 Using a Pandoc Lua filter (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

5.2 Indent text


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

5.3 Control the width of text output


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 5.1: Normal text output that is too wide.

FIGURE 5.2: Text output wrapped with the listings package.

5.4 Control the size of plots/images


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

5.5 Figure alignment


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

5.6 Verbatim code chunks


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

5.6.1 Show a verbatim inline expression


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
5.7 Line numbers for code blocks (*) 15

5.7 Line numbers for code blocks (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

5.8 Multi-column layout (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

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.

6.1 Add LaTeX code to the preamble


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.2 Pandoc options for LaTeX output


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.3 Add logo to title page


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 6.1: A logo on a LaTeX title page.

17
18 6 LaTeX Output

6.4 Include additional LaTeX packages


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.4.1 Loading LaTeX packages


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.4.2 Example packages


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.5 Control the placement of figures


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.5.1 Floating environments


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.5.2 Prevent figures from floating


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.5.3 Force floats forward


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
6.6 LaTeX sub-figures 19

TABLE 6.1: Default LaTeX float settings.

6.5.4 Adjust LaTeX placement rules (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.6 LaTeX sub-figures


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.7 Render documents containing Unicode characters


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.8 Generate a LaTeX fragment


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.9 Add custom headers and footers (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
20 6 LaTeX Output

6.10 Use a custom Pandoc LaTeX template (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.11 Write raw LaTeX code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

6.12 For hardcore LaTeX users (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
7
HTML Output

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.1 Apply custom CSS


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.2 Center section headings


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.3 Style code blocks and text output


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.4 Scrollable code blocks (*)


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.5 Fold all code blocks but show some initially


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.6 Put content in tabs


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

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.

7.8 Embed arbitrary files 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.

7.9 Use a custom HTML template (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
7.10 Include the content of an existing HTML file (*) 23

7.10 Include the content of an existing HTML file (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.11 Add a custom browser icon


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.12 Use the <details> disclosure element


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 7.1: Wrap text output in the details element.

7.13 Sharing HTML output on the web


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.13.1 R-specific services


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.13.2 Static website services


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
24 7 HTML Output

7.14 Improve accessibility of HTML pages


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

7.15 For hardcore HTML users (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
8
Word

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

8.1 Custom Word templates


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 8.1: Find the styles of a specific document element.

FIGURE 8.2: Modify the styles of an element in a Word document.

FIGURE 8.3: Modify the styles of tables in a Word document.

8.2 The two-way workflow between R Markdown and Word


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

8.3 Style individual elements


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
9
Multiple Output Formats

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

9.1 LaTeX or HTML output


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

9.2 Display HTML widgets


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

9.3 Embed a web page


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 9.1: Embed Yihui’s homepage as an iframe or screenshot.

27
28 9 Multiple Output Formats

9.4 Multiple figures side by side


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 9.2: Side-by-side figures.

9.5 Write raw content (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

9.6 Custom blocks (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

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.

9.6.2 Adding a shaded box


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

9.6.3 Including icons


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
10
Tables

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1 The function knitr::kable()


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.1 Supported table formats


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.2 Change column names


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.3 Specify column alignment


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.4 Add a table caption


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

TABLE 10.1: An example table caption.

29
30 10 Tables

TABLE 10.2: Two tables placed side by side.

TABLE 10.3: Two tables created by knitr::kables().

10.1.5 Format numeric columns


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.6 Display missing values


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.7 Escape special characters


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.8 Multiple tables side by side


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.9 Generate multiple tables from a for-loop (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.10 Customize LaTeX tables (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.1.11 Customize HTML tables (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
10.2 The kableExtra package 31

FIGURE 10.1: A striped table created with HTML and CSS.

10.2 The kableExtra package


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.2.1 Set the font size


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.2.2 Style specific rows/columns


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.2.3 Group rows/columns


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.2.4 Scaling down wide tables in LaTeX


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

10.3 Other packages for creating tables


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
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.

11.1 Use variables in chunk options


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.2 Do not stop on error


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.3 Multiple graphical output formats for the same plot


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.4 Cache time-consuming code chunks


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

11.5 Cache a code chunk for multiple output formats


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.6 Cache large objects


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.7 Hide code, text output, messages, or plots


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.8 Hide everything from a chunk


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.9 Collapse text output blocks into source blocks


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
11.10 Reformat R source code 35

11.10 Reformat R source code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.11 Output text as raw Markdown content (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.12 Remove leading hashes in text output


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.13 Add attributes to text output blocks (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.14 Post-process plots (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
36 11 Chunk Options

11.15 High-quality graphics (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 11.1: A plot rendered via the tikz device.

11.16 Step-by-step plots with low-level plotting functions (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.17 Customize the printing of objects in chunks (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

11.18 Option hooks (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
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.

12.1 Redact source code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

12.2 Add line numbers to source code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

12.3 Scrollable text output


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

12.4 Truncate text output


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 (*)

12.5 Output figures in the HTML5 format


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
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.

13.1 Crop plots


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 13.1: A plot that is not cropped.

FIGURE 13.2: A plot that is cropped.

13.2 Optimize PNG plots


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

13.3 Report how much time each chunk takes to run


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 (*)

13.4 Show the chunk header in the output


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

13.5 Embed an interactive 3D plot with rgl


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

FIGURE 13.3: A 3D scatterplot generated from the rgl package.


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.

14.1 Reuse code chunks


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.1.1 Embed one chunk in another chunk (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.1.2 Use the same chunk label in another chunk


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.1.3 Use reference labels (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.2 Use an object before it is created (*)


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

14.3 Exit knitting early


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.4 Generate a plot and display it elsewhere


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.5 Modify a plot in a previous code chunk


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.6 Save a group of chunk options and reuse them (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.7 Use knitr::knit_expand() to generate Rmd source


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
14.8 Allow duplicate labels in code chunks (*) 43

14.8 Allow duplicate labels in code chunks (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.9 A more transparent caching mechanism


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.9.1 Invalidate the cache by changing code in the expression


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.9.2 Invalidate the cache by changes in global variables


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.9.3 Keep multiple copies of the cache


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

14.9.4 Comparison with knitr’s caching


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
15
Other Languages

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.1 Register a custom language engine (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.2 Run Python code and interact with Python


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.3 Execute content conditionally via the asis engine


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.4 Execute Shell scripts


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.5 Visualization with D3


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

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.

15.6.1 Write to a CSS file


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.6.2 Include LaTeX code in the preamble


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.6.3 Write YAML data to a file and also display it


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.7 Run SAS code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
15.8 Run Stata code 47

15.8 Run Stata code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.9 Create graphics with Asymptote


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.9.1 Generate data in R and read it in Asymptote


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

15.10 Style HTML pages with Sass/SCSS


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
16
Managing Projects

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.1 Source external R scripts


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.2 Read external scripts into a chunk


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.3 Read multiple code chunks from an external script (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.4 Child documents (*)


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

16.5 Keep the plot files


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.6 The working directory for R code chunks


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

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.

FIGURE 16.3: Autocomplete file paths in an Rmd document in RStudio.

16.7 R package vignettes


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.8 R Markdown templates in R packages


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
16.9 Write books and long-form reports with bookdown 51

16.8.1 Template use-cases


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.8.2 Template setup


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.9 Write books and long-form reports with bookdown


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

16.10 Build websites with blogdown


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
17
Workflow

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

17.1 Use RStudio keyboard shortcuts


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

17.2 Spell-check R Markdown


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

17.3 Render R Markdown with rmarkdown::render()


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

TABLE 17.1: RStudio keyboard shortcuts related to R Markdown.

53
54 17 Workflow

17.4 Parameterized reports


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

17.5 Customize the Knit button (*)


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

17.6 Collaborate on Rmd documents through Google Drive


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

17.7 Organize an R Markdown project into a research website with


workflowr
This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

17.8 Send emails based on R Markdown


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
18
knitr’s Chunk and Package Options

This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1 Chunk options


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1.1 Code evaluation


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1.2 Text output


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1.3 Code decoration


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.

18.1.7 Code chunk


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1.8 Child documents


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1.9 Language engines


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1.10 Option templates


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1.11 Extracting source code


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

18.1.12 Other chunk options


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.
18.2 Package options 57

18.2 Package options


This PDF is only a skeleton. Please either read the free online HTML version,
or purchase a hard-copy of this book.

You might also like