If you want to generate your document or book in multiple formats

Bob Santos
9 min readDec 19, 2020

Though I code in both R and Python, R Markdown is my only route for writing reports, blogs or books. It is incredibly flexible, has many beautiful design options and supports many output formats really nicely.

If you have never worked in R Markdown, I highly recommend it. If you have worked in it before, here are ten little tricks I’ve learned which have served me well in numerous projects, and which highlight how flexible it is.

https://247sports.com/high-school/mississippi/board/football-102607/contents/watch-northwestern-vs-ohio-state-live-stream-free-reddit-157304868/
https://247sports.com/high-school/mississippi/board/football-102607/contents/live-northwestern-vs-ohio-state-live-stream-ncaaf-157304894/
https://247sports.com/high-school/mississippi/board/football-102607/contents/livestreamnorthwestern-vs-ohio-state-live-free-157304898/
https://247sports.com/high-school/mississippi/board/football-102607/contents/livestreamnorthwestern-vs-ohio-state-live-stream-reddit-157304901/
https://247sports.com/high-school/mississippi/board/football-102607/contents/streamingnorthwestern-vs-ohio-state-live-stream-157304906/
https://247sports.com/high-school/mississippi/board/football-102607/contents/watch-northwestern-vs-ohio-state-live-stream-free-reddit-157304868/
https://247sports.com/high-school/mississippi/board/football-102607/contents/live-northwestern-vs-ohio-state-live-stream-ncaaf-157304894/
https://247sports.com/high-school/mississippi/board/football-102607/contents/livestreamnorthwestern-vs-ohio-state-live-free-157304898/
https://247sports.com/high-school/mississippi/board/football-102607/contents/livestreamnorthwestern-vs-ohio-state-live-stream-reddit-157304901/
https://247sports.com/high-school/mississippi/board/football-102607/contents/streamingnorthwestern-vs-ohio-state-live-stream-157304906/
https://247sports.com/high-school/mississippi/board/football-102607/contents/redditstreamstexas-am-vs-tennessee-live-stream-reddit-fre-157305013/
https://247sports.com/high-school/mississippi/board/football-102607/contents/ncaaf-stream-texas-am-vs-tennessee-live-streamreddit-157305014/
https://247sports.com/high-school/mississippi/board/football-102607/contents/ncaafstreamstexas-am-vs-tennessee-live-stream-reddit-free-157305015/
https://247sports.com/high-school/mississippi/board/football-102607/contents/live-texas-am-vs-tennessee-live-streaming-reddit-ncaaf-free-157305016/
https://247sports.com/high-school/mississippi/board/football-102607/contents/streamsncaaf-texas-am-vs-tennessee-2020-livestream-157305017/
https://247sports.com/high-school/mississippi/board/football-102607/contents/liveoklahoma-vs-iowa-state-live-stream-157305155/
https://247sports.com/high-school/mississippi/board/football-102607/contents/ncaaf-streamsredditoklahoma-vs-iowa-state-live-free-157305156/
https://247sports.com/high-school/mississippi/board/football-102607/contents/streamsncaaf-oklahoma-vs-iowa-state-2020-livestream-157305157/
https://247sports.com/high-school/mississippi/board/football-102607/contents/redditstreamsoklahoma-vs-iowa-state-live-stream-reddit-fre-157305158/
https://247sports.com/high-school/mississippi/board/football-102607/contents/streamredditoklahoma-vs-iowa-state-live-streamsreddit-157305159/
https://www.game.tv/tournaments/Northwestern-vs-Ohio-State-Palace-Stream--678aa6639ff44da8a69c37fde023c435
https://www.game.tv/tournaments/Northwestern-vs-Ohio-State-Palace-Stream-Reddit--ef486c35ce09430280b65f43aa2d882d
https://www.game.tv/tournaments/Northwestern-vs-Ohio-State-Palace-Stream-Free--4fc33ba2231943ad96ebd57711616b78
https://www.game.tv/tournaments/Texas-AM-vs-Tennessee-Palace-Stream-Free--ebfd93d0047c491a90bc61c248a22fb4
https://www.game.tv/tournaments/Texas-AM-vs-Tennessee-Palace-Stream--f67d3d21412b4684bfb74be1f9f7f605
https://www.game.tv/tournaments/Texas-AM-vs-Tennessee-Palace-Stream-Reddit--53e67c69b3f748168b356bfc2aeacfc7
https://www.game.tv/tournaments/Oklahoma-vs-Iowa-State-Palace-Stream-Reddit--38fab0ae4fc347e596dd0ea19170e73d
https://www.game.tv/tournaments/Oklahoma-vs-Iowa-State-Palace-Stream--7748d60ecf79427bb122c609904be057
https://www.game.tv/tournaments/Oklahoma-vs-Iowa-State-Palace-Stream-Free--844db77fa1a145529058e82e87fe3a15

1. Parameterizing documents

So you write a lovely R Markdown document where you’ve analyzed a whole bunch of facts about dogs. And then you get told — ‘nah, I’m more interested in cats’. Never fear. You can automate a similar report about cats in just one command if you parameterize your R markdown document.

You can do this by defining parameters in the YAML header of your R Markdown document, and giving each parameter a value. For example:

---
title: "Animal Analysis"
author: "Keith McNulty"
date: "18 December 2020"
output:
html_document:
code_folding: "hide"
params:
animal_name:
value: Dog
choices:
- Dog
- Cat
- Rabbit
years_of_study:
input: slider
min: 2000
max: 2019
step: 1
round: 1
sep: ''
value: [2010, 2017]
---

Now you can write these variables into the R code in your document as params$animal_name and params$years_of_study. If you knit your document as normal, it will knit with the default values of these parameters as per the value variable. However, if you knit with parameters by selecting this option in RStudio’s Knit dropdown (or by using knit_with_parameters()), a lovely menu option appears for you to select your parameters before you knit the document. Awesome! More instructions here.

Knitting with parameters (Image by author)

2. xaringan

xaringan is an R package that uses R markdown to create pretty, professional slide presentations that look neat but also print well (not something you can take for granted with web slides).

It’s easy to customize thexaringan layout, highlight code and output, insert graphics, code and all the other good things that you’d expect to do in R Markdown. Here is an example of a recent training presentation I created with xaringan and a link to its Github code. More on xaringan here.

Beautiful, clean xaringan slide layout (Image by author)

3. Run Python code

You don’t have to embed R code in R Markdown. It accepts and runs a wide range of languages. In particular you can run Python code and even use Python outputs in later R code.

To run Python code inside R Markdown, you need to have the reticulate package installed make sure that your session is pointing to a Python environment that has all of the packages you need. One way to do this is to set the RETICULATE_PYTHON environment variable to the path to the python executable in the conda environment or virtualenv that you want to work. You can do this by adding this to a .Rprofile file which will run every time you launch your project.

Sys.setenv(RETICULATE_PYTHON = "path_to_env/bin/python3")

Then, to write and execute Python code you just need to wrap it as follows:

```{python}# write python code```

You can see an example in action in the Python section of my book here, and if you follow the links to the source you can see the code behind it.

4. Pimp your R Markdown with prettydoc

prettydoc is a package by Yixuan Qiu which offers a simple set of themes to create a different, prettier look and feel to your RMarkdown documents. This is super helpful when you just want to jazz up your documents a little but don’t have time to get into the styling of them yourself.

It’s really easy to use. Simple edits to the YAML header of your document can invoke a specific style theme throughout the document, with numerous themes available. For example, this will invoke a lovely clean blue coloring and style across titles, tables, embedded code and graphics:

---
title: "My doc"
author: "Me"
date: June 3, 2019
output:
prettydoc::html_pretty:
theme: architect
highlight: github
---

More on prettydoc here.

5. Optionally hide your code in R Markdown with code_folding

RMarkdown is a great way to record your work, allowing you to write a narrative and capture your code all in one place. But sometimes your code can be overwhelming and not particularly pleasant for non-coders who are trying to read just the narrative of your work and are not interested in the intricacies of how you conducted the analysis.

Previously the only options we had were to either set echo = TRUE or echo = FALSE in our knitr options to either show our code in the document or not. But now we can set an option in the YAML header that gives us the best of both worlds. Setting code_folding: hide in the YAML header will hide the code chunks by default, but provide little click-down boxes in the document so that the reader can view all the code, or particular chunks, as and when they want to, like this:

Code folding drop downs in R Markdown (Image by author)

6. Bookdown

Maybe you want to write a technical book, or maybe your paper/write-up is so big that you need to split it into chapters. bookdown is an R package which allows you to construct a book structure to your output. You can write your chapters in separate R Markdown files headed with # level headings. You can employ an easy reference format to reference a bibliography or other other sections, chapters, figures or tables. You can then render the entire book in some neat HTML formats like Gitbook or Bootstrap, or you can render it as a pdf or epub format. Here’s an example of a recent book I wrote in Gitbook and in Bootstrap 4 (development version of bookdown). More on bookdown here.

The beautiful new Bootstrap 4 Book format in the development version of bookdown (Image by author)

7. Use interactive graphics in your documents by embedding plotly

It’s a really effective teaching tool to allow your readers to interact with your data or graphics as part of your R markdown documents. Personally I love plotly for generating interactive graphics in 2D and 3D. You can insert plotly code into a code chunk in an R Markdown document (it can be coded in R or Python — see Point 3), and this will generate a beautiful graphic that the reader can interact with to see data points, rotate, or whatever. Here’s an example. More on plotly here.

Using plotly graphics to allow user interaction (Image by author)

8. Swap your code according to the output format

If you want to generate your document or book in multiple formats — like in HTML and PDF — you might need to adjust your output for each. For example, you can’t put the interactive graphic above in a PDF. But you also don’t want to be managing multiple versions of the same source files for the different outputs.

It’s easy to make the code in your code chunks conditional on the output format. For example, if you want to use a static graphic for PDF and an interactive graphic for HTML, this will work in your code chunk:

if (knitr::is_latex_output()) {
# insert code for static graphic
} else {
# insert code for interactive graphic
}

9. Beautifully aligned math

If you have to put math in R Markdown you can use LaTeX math notation. You’ll need to install LaTeX, and the best way to do that is to install the tinytex package (this is an easier and much smaller installation than the full LaTeX installation which is about 5 Gigabytes!!!). You can write math inline by placing it between $ symbols. If you want the math in its own section you can place it between $$ symbols in a new paragraph. If you know LaTeX, you can take advantage of all its features inside the $$ symbols. Here’s an excellent guide to LaTeX, and here is an example of some beautifully aligned math derivations:

Using LaTeX Math features in R Markdown (Image by Author)

10. Patchwork

If you are putting multiple ggplots together, the patchwork package uses an intuitive and simple grammar so that you don't have to use more complicated functions like grid.arrange(). It also has more capabilities than cowplot to handle complex layouts.

With each plot assigned to an object, you can use characters like | and / to specify what you want aligned in columns and what you want in rows, and the package will do the alignment for you. Here's an example from the package Github repo using mtcars:

library(ggplot2)
library(patchwork)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
p4 <- ggplot(mtcars) + geom_bar(aes(carb)) (p1 | p2 | p3) /
p4

From the patchwork Github repo

I hope these little examples help you see how amazingly versatile R Markdown is. There is a wide and growing range of output formats and designs, and an increasingly flexible codebase to help you tailor your documents to achieve the precise look and content you want. Increasingly, also, R Markdown is the basic building block of other publishing tools like bookdown and blogdown. If you haven’t used R Markdown yet, here is a great starting point.

Originally I was a Pure Mathematician, then I became a Psychometrician and a Data Scientist. I am passionate about applying the rigor of all those disciplines to complex people questions. I’m also a coding geek and a massive fan of Japanese RPGs. Find me on LinkedIn or on Twitter. Also check out my blog on drkeithmcnulty.com.

--

--