R Markdown - create "loop" slides based on data frame values

A couple years ago I wrote a post on how to "mail merge" an Excel table in PowerPoint; i.e., create slides based on information in each row of an Excel table.

Occasionally I am asked how to do something similar with slides containing images. I figured R Markdown might be a good tool for this.

Let's say I have this below data frame.

slides <- data.frame(Name = c("Jack", "Joe", "Susan", "Hetta"),
                     Hometown = c("New York", "Philadelphia", "Boston", "Berlin"),
                     Headshot = c("H:/slides/jack.jpg",

I want to create a slide for each row of the data frame in the style of:

### Name
- Hometown


Any thoughts? What I ended up doing for now is to paste the fields that I need together with R Markdown styling into a new column and paste that output into a .rmd file (like below) but I would think there's a much more efficient solution here.

I suppose this would be something like a loop but I'm not familiar with how they work to generate text in R Markdown.

slides$md <- paste0("### Name: ", slides$Name,
                    "\n - Hometown: ", slides$Hometown,
                    "\n\n ![](", slides$Headshot, ")\n\n --- \n\n")

### Name: Jack
 - Hometown: New York



 ### Name: Joe
 - Hometown: Philadelphia



 ### Name: Susan
 - Hometown: Boston



 ### Name: Hetta
 - Hometown: Berlin



Not sure if I'm answering your question, but here's another way of doing the same thing but using the glue package. The advantage of this approach is that it's much easier to read the slide template.

Here's the Rmd source you could use to create 4 slides with images in the same style as the ones in your post.

```{r include=FALSE}

slides_info <- tibble::tribble(
      ~name,  ~hometown, ~img_url,
   "Sharon", "New York", "https://images.unsplash.com/photo-1525267219888-bb077b8792cc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjUzMTAyfQ",
      "Kal",   "Boston", "https://images.unsplash.com/photo-1520813792240-56fc4a3765a7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjUzMTAyfQ",
     "Gill",  "Houston", "https://images.unsplash.com/photo-1528111368067-474f7accad70?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjUzMTAyfQ",
  "Emerson",  "Chicago", "https://images.unsplash.com/photo-1524112895789-54005634716d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjUzMTAyfQ"

slides_text <- glue_data(
  ### {name}

  Hometown: {hometown}  

`r slides_text %>% paste(collapse = "\n---\n")`

If you use xaringan, you can use autoplay to automatically advance through the slides. To do that, include the following lines in your YAML header.

    lib_dir: libs
    seal: false  #<< turn off title slide
      autoplay: 2000 #<< next slide every 2 seconds

It did and more, thank you. Nice touch with xaringan too.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.