Ten Remarkable R Markdown Techniques for Enhanced Reporting
Written on
Chapter 1: Introduction to R Markdown
R Markdown offers greater versatility than you may initially perceive.
Despite my proficiency in both R and Python, R Markdown serves as my primary tool for crafting reports, blogs, and books. Its remarkable adaptability, aesthetic design options, and exceptional support for various output formats make it invaluable. If you're new to R Markdown, I highly recommend giving it a try. For those already familiar with it, here are ten effective tricks I've picked up that underscore its flexibility.
Section 1.1: 1. Parameterizing Documents
Imagine you've created a delightful R Markdown report analyzing numerous aspects of dogs, only to find out that your audience prefers cats. Fear not! By parameterizing your R Markdown document, you can seamlessly generate a similar report for cats with just one command.
This process begins with defining parameters in the YAML header of your R Markdown document and assigning values to each parameter. 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]
You can incorporate these variables into your R code using params$animal_name and params$years_of_study. When knitting your document, it will utilize the default parameter values. However, if you choose to knit with parameters using the option in RStudio's Knit dropdown (or by employing knit_with_parameters()), a user-friendly menu will allow you to select your parameters before knitting the document.
Section 1.2: 2. Utilizing xaringan
The xaringan package enables you to create elegant, professional slide presentations from R Markdown that look great both on-screen and in print. Customizing the layout, highlighting code and output, and embedding graphics is a breeze with xaringan. Here's a snapshot of a recent training presentation I crafted using this tool, along with a link to its GitHub repository.
More details on xaringan can be found here.
Chapter 2: Advanced Techniques
The first video titled "8 Tips and Tricks on R Markdown & Where have I been" provides insights into effective R Markdown usage.
The second video, "R Markdown Tutorial for Beginners | RStudio Tutorials Part 1," serves as a beginner-friendly guide to R Markdown.
Section 2.1: 3. Executing Python Code
R Markdown is not limited to R code; it supports various programming languages, including Python. To execute Python code within an R Markdown document, ensure the reticulate package is installed and that your session points to a suitable Python environment.
You can set the RETICULATE_PYTHON environment variable to the path of the Python executable in your desired environment. To write and execute Python code, simply wrap it as follows:
# write python code
For more examples, refer to the Python section of my book.
Section 2.2: 4. Enhancing R Markdown with prettydoc
The prettydoc package by Yixuan Qiu offers various themes to give your R Markdown documents a more appealing look and feel. This is particularly useful for quick styling without delving deep into customization.
Applying a specific theme is as simple as modifying the YAML header:
title: "My doc"
author: "Me"
date: June 3, 2019
output:
prettydoc::html_pretty:
theme: architect
highlight: github
Learn more about prettydoc here.
Section 2.3: 5. Hiding Code with Code Folding
While R Markdown serves as an excellent platform for documenting your work, the code can sometimes overwhelm readers who are more interested in the narrative. Previously, you could only choose to show or hide code using echo = TRUE or echo = FALSE.
Now, by adding code_folding: hide to your YAML header, you can hide the code chunks by default while allowing readers to expand them at will.
Section 2.4: 6. Crafting Books with Bookdown
For those interested in writing technical books or lengthy papers, the bookdown package allows you to structure your output into chapters easily. Each chapter can be a separate R Markdown file, and you can easily reference various elements like bibliographies and figures.
Here’s an example of a book I created using Gitbook and Bootstrap 4 formats in bookdown.
Section 2.5: 7. Integrating Interactive Graphics with Plotly
Enhancing your R Markdown documents with interactive graphics can significantly improve reader engagement. By using the plotly package, you can create interactive 2D and 3D graphics that readers can manipulate directly.
Insert plotly code within a code chunk, and it will generate graphics that allow for interaction. Explore more about plotly here.
Section 2.6: 8. Adjusting Code Based on Output Format
When generating documents in multiple formats, such as HTML and PDF, you may need to adapt your code accordingly. For instance, you might want to use a static graphic for PDF output while employing an interactive one for HTML.
You can conditionally manage your code based on the output format using:
if (knitr::is_latex_output()) {
# insert code for static graphic
} else {
# insert code for interactive graphic
}
Section 2.7: 9. Aligning Mathematical Notation
When including mathematical expressions in R Markdown, you can utilize LaTeX math notation. For a streamlined installation, consider the tinytex package, which simplifies the LaTeX setup process.
You can write inline math using $ symbols or create standalone equations with $$ symbols. For those familiar with LaTeX, you’ll find its features available within R Markdown.
Section 2.8: 10. Creating Multi-Plot Layouts with Patchwork
The patchwork package allows for intuitive combinations of multiple ggplots without the complexities of functions like grid.arrange(). With a straightforward syntax, you can easily align plots in rows and columns.
Here’s a simple example from the package's GitHub repository:
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
In conclusion, these examples highlight the impressive versatility of R Markdown. With an ever-expanding array of output formats and designs, R Markdown is increasingly becoming the foundational tool for other publishing platforms such as bookdown and blogdown. If you haven't yet explored R Markdown, I encourage you to start now.
Originally, I pursued a career in Pure Mathematics before transitioning to Psychometrics and Data Science. My passion lies in applying rigorous methodologies to complex human-centric questions. Connect with me on LinkedIn or Twitter, and explore my blog at drkeithmcnulty.com.