randy.pub

Personal homepage
Author Randy Boyes
Updated
Nav Home Publications Resume Posts

Goal

Inspired by a post I saw on Bluesky, what is the easiest way to knit a quarto document that contains a dynamic number of figures - e.g. a plot for each question in a survey?

Solution

The best way I've found is to use two files: one for the main document, and one that will serve as the "template" for the figures. The main document will have a loop that calls knit_child with the template multiple times.

Here's a simple example:

Main File

---
title: "Variable Number of Figures"
format: typst
---

# An Example Report

```{r, include = FALSE}
library(tibble)
library(dplyr)
library(ggplot2)

knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(message = FALSE)
knitr::opts_chunk$set(warning = FALSE)

data <- tibble(
    q = rep(c("1", "2", "3"), each = 100),
    v = c(runif(100), rnorm(100), rexp(100))
)
```

```{r, results = "hide"}
out = NULL
for(q in unique(data$q)){
    question <- q
    out <- c(out, knitr::knit_child("child.qmd"))
}
```

```{r, results = "asis"}
cat(paste(out, collapse="\n") )
```

child.qmd

# Question `r q`

```{r, results = "hide"}
dist = case_when(
  q == "1" ~ "Uniform",
  q == "2" ~ "Normal",
  TRUE ~ "Exponential")
```

Some random data from the `r dist` distribution.

```{r}
ggplot(filter(data, q == question)) +
    geom_histogram(aes(x = v))
```

Result

The pdf document that is generated by rendering or previewing the main document in quarto is available here.


MIT License Randy Boyes. Website built with Franklin.jl and the Julia programming language. Design inspired by The Monospace Web. Code for this website is available on Github.