Include Images in R Markdown PowerPoint

I learned about the R Markdown powerpoint_presentation output format at rstudio::conf 2019.

Recently I used the feature to organize a set of previously generated plots (saved as .png files) into a single PowerPoint, which was the output format of choice for one collaborator.

Including a single image file in an R Markdown powerpoint_presentation is the same as any other Markdown document:

![alt_text](path_to_image.extension)

However, including many image files (in my case dozens) would involve tediously repeating that pattern. This post details how to create a loop that generates the code to render every image in a given directory as its own slide in a PowerPoint presentation.

Example

First we will create example images. This demo uses the msleep dataset from ggplot2. Here we are generating the images in a separate R script and then writing them to .png files to be rendered together in a single output document via R Markdown.

Note that this is a contrived example. If we were truly starting from scratch, we could use the code below to render the plots directly in R Markdown without saving them as .png files at all. However, for my original use-case I already had the image files generated.

library(tidyverse)

## create a list of msleep tibbles split by vore
by_vore <- group_split(msleep, vore)

## make a dir to write the plots
vp_dir <- "vore-plots"
if(!dir.exists(vp_dir)) dir.create(vp_dir)

## loop over each vore and plot the sleep total by bodywt
for(vore in by_vore) {
  
  vore_name <- unique(vore$vore)
  
  ## create the ggplot2 object
  p <-
    ggplot(vore, aes(sleep_total, bodywt)) +
    geom_point() +
    scale_y_log10() +
    ggtitle(label = sprintf("Sleep by body weight (%s-vore)", vore_name)) +
    theme_bw()
  
  print(p)
  
  ## save the plot to a disk
  ggsave(p, filename = sprintf("%s/%s.png", vp_dir, vore_name))
}

Now that we have the plots saved to disk, we can create the R Markdown document. This file (here named vore_plots.Rmd) will use the output: powerpoint_presentation option in the YAML frontmatter. In the body of the .Rmd we need a code chunk to generate the raw Markdown text for adding each image to its own slide. This chunk needs to have the results='asis' option set for the text issued from cat() to render correctly:

    ---
    title: 'vore plots'
    output: powerpoint_presentation
    ---
    
    ```{r results='asis'}
    vps <- list.files('vore-plots', full.names = TRUE)
    
    for(vp in vps) {
      cat('##')
      cat('\n')
      cat(paste0('![](', vp, ')'))
      cat('\n')
      cat('\n')
    }
    ```

To generate to the .pptx output use the Knit button in the RStudio IDE or call rmarkdown::render() at the console:

rmarkown::render("vore_ppt.Rmd")

Related