How to include a multipage PDF in RMarkdown with dynamic paths?

I was able to figure out how to include a multi-page PDF document in my RMarkdown output using "\includepdf", but I need to be able to change the path to different PDFs based on conditions in the data. I’d like to be able to call the PDF file path based on an object I set in a chunk beforehand (e.g. "test"). Any ideas?
Thanks!

---
title: "Personnel Reports"
output:
  pdf_document
header-includes:
  - \usepackage{pdfpages}
---

This works:

\includepdf[pages=-,pagecommand={}]{Person1_report.pdf}

```{r global_options, include=FALSE}
test <- "Person2_report.pdf"
```' 
This doesn't work: 
\includepdf[pages=-,pagecommand={}]{test}

>Solution :

---
title: "Personnel Reports"
output:
  pdf_document:
    keep_tex: true
header-includes:
  - \usepackage{pdfpages}
---

```{r global_options, include=FALSE}
test <- "example-image-duck.pdf"
```

\includepdf[pages=-,pagecommand={}]{`r test`}

Leave a Reply