How can I include R code in an Rmarkdown figure caption?

I'd like to include R code in an Rmarkdown figure caption that then renders to PDF.

```{r parameters}

insert_custom <- "world"

```

followed by

```{r hello-world, fig.cap = "Hello `r insert_custom`"}

plot(rnorm(10))

```

Thanks!

1 Like

Use fig_caption: true in your YAML and opts_knit$set(eval.after = "fig.cap")

---
title: "Example"
output:
  pdf_document:
    fig_caption: true
---

```{r parameters}
library(knitr)
opts_knit$set(eval.after = "fig.cap")
insert_custom <- "world"
```

followed by

```{r hello-world, fig.cap = paste('Hello', insert_custom)}
plot(rnorm(10))
```

8 Likes

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