The other day I needed a template to create a table of images in an Rmarkdown document.
I found a few stack overflow posts, but nothing that really addressed this issue, so I wanted to document the template I came up with in a short post.
To clarify: I had a large number of images, not generated in the Rmd, that had to be displayed. If you are interested in displaying your plots generated in the Rmd, this approach is overkill. Instead you may want to take a look at this post by Karl Broman.
Below is the YAML portion of the Rmd file. I provide a document title, set the output type as html_document, and specify that I don’t want markdown in between my HTML blocks. This will ensure the tables I create will render correctly and not just as HTML text. To learn more about the md_extensions check out this page.
Create Plots and Save images
Below is my base RProject stucture. I have the Rproj file and a directory labeled as doc in the main project directory. In the doc subdirectory is the Rmd file and an empty directory labeled as figures where I will store the plots I generate.
To generate some plots I use the code below. After generating each plot I save it as a png file. I’m aware you could display plots in a grid format using only R, but the premise of this post is about displaying image files in a table. The code below creates 4 directories with 12 plots each resulting in a total of 48 plots.
Create the HTML Document
Below is the code chunk for generating the HTML table of images in the Rmd file.
For each of the figures subdirectories a single table is made. Each row
of the table contains 4 columns containing an image in each cell. Each table is
3 rows (3 rows, 4 columns, 12 cells total).
Below is the resulting directory structure after knitting the Rmd document to HTML.
Below is an example of one of the tables. The complete document can be seen
by clicking on the image below.
A Final Note
This template will only work for creating HTML documents. HTML tables won’t be
rendered correctly into PDF via Pandoc (or maybe I should say I haven’t figured
out how to do this in an easily reproducable fashion). That being said, I’ll be following
up this post with a template for creating a table of images using LaTeX in RMarkdown.