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.
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.

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.

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](http://peopleanalytics-regression-book.org/alt-approaches.html#inferential-statistical-modeling-in-python), 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](http://yixuan.cos.name/prettydoc/).
### 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:

### 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](http://peopleanalytics-regression-book.org/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](http://peopleanalytics-regression-book.org/index.html) (development version of `bookdown`). More on `bookdown` [here](https://bookdown.org/yihui/bookdown/).

### 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](https://plotly.com/r/).

### 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](https://www.latex-tutorial.com/tutorials/) to LaTeX, and here is an example of some beautifully aligned math derivations:

### 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](https://github.com/thomasp85/patchwork) 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
`](https://miro.medium.com/1*2ikrisluofzFdjPgkAqJpw.png)
I hope these little examples help you see how amazingly versatile R Markdown is. T[here](https://rmarkdown.rstudio.com/lesson-1.html) 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](https://www.linkedin.com/in/keith-mcnulty/) or on [Twitter](https://twitter.com/dr_keithmcnulty). Also check out my blog on [drkeithmcnulty.com](http://drkeithmcnulty.com/)._
