Pimp my RMD: a few tips for R Markdown
logo



R markdown creates interactive reports from R code. This post provides a few tips I use on a daily basis to improve the appearance of output documents. In any case, an unavoidable resource is the Rstudio documentation.

Text formating


R markdown allows to easily format your text. You can add links, write in bold or italic. This is very well explained in the Rstudio cheatsheet.

Here is the code I used to make this paragraph:

R markdown allows to easily format your text. You can add [links](www.r-graph-gallery.com), write in **bold** or *italic*. This is very well explained in the [Rstudio cheatsheet](https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf).

Horizontal lines


Add an horizontal line by adding 3 stars:

***

Chapter auto numbering


Header of level 1, 2, 3 are set using #, ## and ###. You can auto number your chapters using this option in the header:

---
title: "Your title"
output: 
  html_document:
    number_sections: TRUE
---

# Title
## A subtitle
## Another subtitle

# Another title

Skip a line


I really like to add spaces in my document to give it a more uncluttered look. This is done using the <br> command. This .rmd code:

A first sentence
<br><br><br><br>
A seconde sentence

will give this htmloutput:


A first sentence



A seconde sentence


Center an image


To center an image, use this code:

<center>
![FigName](logo_r_graph_gallery.jpg)
</center>
Here is the result
FigName

White space around img


If you’re struggling with to much white space around your image, try to play with the fig.asp argument. Here I used fig.asp=0.50.

library(png)
library(grid)
img <- readPNG("kan.png")
grid.raster(img)
Lovely Kangaroo from the Mornington Peninsula.

Lovely Kangaroo from the Mornington Peninsula.

Note: thanks to Anna Quaglieri for this suggestion.

Space before title


I find it pleasant to have a bit of space before starting a new chapter. You can use a <br> before each header. A more convenient way is to add some margin in your CSS. Create a style.css file:

h1, .h1, h2, .h2, h3, .h3 {
    margin-top: 84px;
}

A rmd document that takes into account this .css file:

---
title: "A document with a CSS included"
output:
  html_document:
    css: style.css
---

A title will follow, but with a lot of space before it

# Title 1

content of part 1

# Title 2

content of part 2

The document you are reading uses this css. See the separation between chapters.

Figures caption


Specify the caption of your figure in the chunk header. Example:

{r, fig.align="center", fig.width=6, fig.height=6, fig.cap="Figure: Here is a really important caption."}
library(tidyverse)
mpg %>%
  ggplot( aes(x=reorder(class, hwy), y=hwy, fill=class)) + 
    geom_boxplot() +
    xlab("class") +
    theme(legend.position="none")
Figure: Here is a really important caption.

Figure: Here is a really important caption.

Custom caption


Change the black default caption using CSS. Adding this code in your style.css file.

<style>
p.caption {
  font-size: 0.9em;
  font-style: italic;
  color: grey;
  margin-right: 10%;
  margin-left: 10%;  
  text-align: justify;
}
</style>
file will give this result:
Figure: Here is a really important caption, customized to be grey and in italic.

Figure: Here is a really important caption, customized to be grey and in italic.

Equations


Insert equation using Latex formating:

A = (π * λ × r4)/α

Delimit Latex syntax with $

$A = (\pi * \lambda \times r^{4}) / \alpha $

2 figures in 2 columns


You can display 2 plots one beside each other. Add out.width=c('50%', '50%'), fig.show='hold' to your chunk header. Something like:

``{r out.width=c('50%', '50%'), fig.show='hold'}
boxplot(1:10)
plot(rnorm(10))
`

Several columns




Since R Markdown use the bootstrap framework under the hood. It is possible to benefit its powerful grid system. Basically, you can consider that your row is divided in 12 subunits of same width. You can then choose to use only a few of this subunits.



Here, I use 3 subunits of size 4 (4x3=12). The last column is used for a plot. You can read more about the grid system here. I got this result showing the following code in my R Markdown document.

Code to get this result:

<div class = "row">
  
<div class = "col-md-4">
<br><br>Since R Markdown use the [bootstrap framework](https://getbootstrap.com/docs/4.0/layout/grid/) under the hood. It is possible to benefit its powerful grid system. Basically, you can consider that your row is divided in 12 subunits of same width. You can then choose to use only a few of this subunits.
</div>
  
<div class = "col-md-4">
<br><br>Here, I use 3 subunits of size 4 (4x3=12). The last column is used for a plot. You can read more about the grid system [here](bootstrap grid system). I got this result showing the following code in my R Markdown document.
</div>
  
<div class = "col-md-4">
``{r, message=FALSE, echo=FALSE}
ggplot( mtcars, aes(x=mpg)) + geom_histogram(fill="skyblue", alpha=0.5) + theme_minimal()
``
</div>
</div>

Tabs for sub-chapters


Save space in your document using buttons or tabs for sub chapters. Result can look like this:

First

content of sub-chapter #1




Here is the code used to create this section:

# Use buttons or tabs for sub-chapters {.tabset .tabset-fade .tabset-pills}
***
Save space in your document using buttons or tabs for sub chapters. Add this code at the end of your title:

## First
A first section

## Second
content of sub-chapter #2

## Third
content of sub-chapter #3

Note that I’ve also custom the buttons using this CSS:

.btn {
    border-width: 0 0px 0px 0px;
    font-weight: normal;
    text-transform: ;
}
.btn-default {
    color: #2ecc71;
    background-color: #ffffff;
    border-color: #ffffff;
}

Second

content of sub-chapter #2

Third

content of sub-chapter #3

Use DT for tables


The DT library is my favourite option to display tables in your document. It allows to:

  • Show only a few line
  • Have a clean appearance
  • Have a research bar to find a specific entry
  • Add filters to each column
  • And much more

Here is an example with the options I use most of the time:

library(DT)
datatable(mtcars, rownames = FALSE, filter="top", options = list(pageLength = 5, scrollX=T) )

Hide code


If you share your code with somebody who’s more focus on results than code, or if your code chunks are very long, you probably want to hide the code, but still allow the reader to consult it if necessary. This is possible by modifying the YAML header of your document:

output:
  html_document:
    code_folding: "hide"

Your code chunks will be hidden in the output, but a small ‘code’ button will be available to display it if necessary.

Highlight a piece of text


You can apply some css to a specific part of your document. Here is an example where I change the background color of a small part. Handy to highlight conclusions at the end of your document.

Code:

<style>
div.blue { background-color:#e6f0ff; border-radius: 5px; padding: 20px;}
</style>
<div class = "blue">

- This is my first conclusion
- This is my second conclusion

</div>
Will give:
  • This is my first conclusion
  • This is my second conclusion

Parallax


Since R Markdown can output an html document, it is possible to apply whatever techniques used in common website. It is thus possible to set a header with a background image in parallax. See an example online here. Here is a glimpse of how it looks like:

You need to custom the css and the header.html files of your document. See the code provided in the corresponding github repository.

Cache code


It is possible to cache a specific chunk adding cache=TRUE in its header. You can also cash the whole document adding knitr::opts_chunk$set(cache=TRUE) in a chunk at the begining of the document.

Use this option with care, I strongly advise to read this document by Yihui Xie on this topic.

Interactive graphics


R allows to build any type of interactive graphic. My favourite library is plotly that will turn any of your ggplot2 graphic interactive in one supplementary line of code. Try to hover points, to select a zone, to click on the legend.

library(ggplot2)
library(plotly)
library(gapminder)
 
p <- gapminder %>%
  filter(year==1977) %>%
  ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) +
  geom_point() +
  scale_x_log10() +
  theme_bw()
 
ggplotly(p)

Theme


You can use any of the bootswatch theme to automatically custom the font and general appearance of your document. You can also control the syntax highlighting style. See the possibilty here. Here is how to call these options in the YAML header:

title: "your title"
output:
  html_document:
    theme: sandstone
    highlight: tango

Template


Customize the document appearance using a template. Two packages offer several templates:


Share it online


Display your html online using github. Follow these steps:

  • You need a github account.
  • Name your .rmd file index.rmd. Knit it to have a index.html file.
  • Create a repository on github with your working folder.
  • On your github online repo go to Settings -> GitHub Pages -> Source -> Master Branch -> Save.
  • Wait a little, your .html file will be available at username.github.io/repoName

An attempt to illustrate it with a few screenshots:

Compile in a website


Explanation in the R Markdown Websites section of the R Markdown documentation. Note that this website is render using this technic. To run a basic example:

library(rmarkdown)
  • build the website doing
rmarkdown::render_site()
  • You now have a _site folder that contains an index.html file. Open it, it is your website. You can host it on github like explained above.

Note that you can go further using the blogdown package to generate static websites based on R Markdown and Hugo. This allows to build awesome websites only with R. It is used by a huge number of R blogs now.

Create template


If you often use the same kind of customization you probably want to create your own .rmd template. A good starting point is the Rstudio documentation.

This document is produced using my personal template: epuRate. I just custom a bit the CSS, added an header and a footer, and created a skeleton with tips I often use. An easy solution to create your template can be to fork / download this repo and apply your own style instead of mine.

Session info


It is a good practice to add a session info at the end of your document. It will increase reproducibility and costs only one line of code

sessionInfo()
## R version 3.4.1 (2017-06-30)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS Sierra 10.12.6
## 
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_AU.UTF-8/en_AU.UTF-8/en_AU.UTF-8/C/en_AU.UTF-8/en_AU.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] bindrcpp_0.2.2  gapminder_0.3.0 plotly_4.7.1    DT_0.4         
##  [5] forcats_0.3.0   stringr_1.3.1   dplyr_0.7.8     purrr_0.2.5    
##  [9] readr_1.1.1     tidyr_0.8.2     tibble_1.4.2    ggplot2_3.1.0  
## [13] tidyverse_1.2.1 rmarkdown_1.9   epuRate_0.1    
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.0        lubridate_1.7.4   lattice_0.20-35  
##  [4] assertthat_0.2.0  rprojroot_1.3-2   digest_0.6.18    
##  [7] psych_1.8.3.3     mime_0.5          R6_2.3.0         
## [10] cellranger_1.1.0  plyr_1.8.4        backports_1.1.2  
## [13] evaluate_0.10.1   httr_1.3.1        highr_0.6        
## [16] pillar_1.2.2      rlang_0.3.0.1     lazyeval_0.2.1   
## [19] readxl_1.1.0      rstudioapi_0.7    data.table_1.11.4
## [22] labeling_0.3      foreign_0.8-70    htmlwidgets_1.2.1
## [25] munsell_0.5.0     shiny_1.1.0       broom_0.4.4      
## [28] compiler_3.4.1    httpuv_1.4.3      modelr_0.1.1     
## [31] pkgconfig_2.0.2   mnormt_1.5-5      htmltools_0.3.6  
## [34] tidyselect_0.2.5  viridisLite_0.3.0 crayon_1.3.4     
## [37] withr_2.1.2.9000  later_0.7.2       grid_3.4.1       
## [40] nlme_3.1-137      jsonlite_1.5      xtable_1.8-2     
## [43] gtable_0.2.0      magrittr_1.5      scales_1.0.0.9000
## [46] cli_1.0.0         stringi_1.2.4     reshape2_1.4.3   
## [49] promises_1.0.1    xml2_1.2.0        tools_3.4.1      
## [52] glue_1.3.0        hms_0.4.2         crosstalk_1.0.0  
## [55] parallel_3.4.1    yaml_2.1.19       colorspace_1.3-2 
## [58] rvest_0.3.2       knitr_1.20        bindr_0.1.1      
## [61] haven_1.1.1

References


Feedback


This document provides a few tips I often use in my documents. I hope it can help. If you know any other tip I should add, please send me an email to yan.holtz.data@gmail.com, or suggest it via the associated github repository.

This page is linked with the R graph gallery and you can also reach me on twitter!

 




A work by by Yan Holtz - 10 December 2018

yan.holtz.data@gmail.com