You can do this by defining parameters in the YAML header of your R

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:

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.

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

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:

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:

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:

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