Search code examples
rlatexr-markdownbeamerpresentation

RMarkdown Beamer make slide titles and add figures in loop


I am new to RMarkdown and Beamer. I am trying to make a set of slides where each slide contains a JPG. I have a dozen to loop through. How do I set this up in a loop?

Here is the RMD file:

---
title: 'slideshow'
output:
  beamer_presentation:
    theme: "AnnArbor"
---

# Introduction

## Blah

- Text
- Here
- Etc.

# Images

## pic_1

```{r echo=FALSE, out.width = '100%'}
knitr::include_graphics("../images/modelA_pic_1.jpg")
```

## pic_2

```{r echo=FALSE, out.width = '100%'}
knitr::include_graphics("../images/modelA_pic_2.jpg")
```

## pic_3

```{r echo=FALSE, out.width = '100%'}
knitr::include_graphics("../images/modelA_pic_3.jpg")
```

## pic_4

```{r echo=FALSE, out.width = '100%'}
knitr::include_graphics("../images/modelA_pic_4.jpg")
```

I know I can put the slide titles and figure paths into a data frame, but I am not sure how to do this inside RMarkdown and how to loop through it to build the slide titles and insert the images.

title <- c('pic_1', 'pic_2', 'pic_3', 'pic_4')
fpath <- c('modelA_pic_1.jpg', 'modelA_pic_2.jpg', 'modelA_pic_3.jpg', 'modelA_pic_4.jpg')
fpath <- paste0("../images/", fpath)
myfiles <- data.frame(title, fpath)

Updated Based on Accepted Answer

Below is what I ended up using for my Rmd. This page explains the basics of the xmpmulti package.

For this set up, my RMD is in one folder; the images are one folder up (../) and then in a folder called temp (../temp/). The images in this folder are named test-1.png, test-2.png, etc.

---
title: 'slideshow'
output:
  beamer_presentation:
    theme: "AnnArbor"
header-includes:
  - \usepackage{xmpmulti}
---

# Introduction

## Blah

- Text
- Here
- Etc.

```{=latex}
\end{frame}
\section{Images}
\begin{frame}
\frametitle<1>{picture 1}
\frametitle<2>{picture 2}
\centering
\multiinclude[format=png,start=1,end=2,graphics={width=1\textwidth}]{../temp/test}
\end{frame}
\begin{frame}
```

some test

Solution

  • Assuming your images are named pic-1.png etc., then beamer has an automatic way to loop over the images via the xmpmulti package:

    ---
    title: 'slideshow'
    output:
      beamer_presentation:
        theme: "AnnArbor"
        keep_tex: true
    header-includes:
      - \usepackage{xmpmulti}
    ---
    
    # Introduction
    
    ## Blah
    
    - Text
    - Here
    - Etc.
    
    ```{=latex}
    \end{frame}
    \section{Images}
    \begin{frame}
    \frametitle<1>{picture 1}
    \frametitle<2>{picture 2}
    \frametitle<3>{picture 3}
    \centering
    \multiinclude[format=png,start=1,end=3,graphics={width=.6\textwidth}]{pic}
    \end{frame}
    \begin{frame}
    ```
    
    some test