Skip to content

Instantly share code, notes, and snippets.

@j-jayes
Created March 4, 2022 11:30
Show Gist options
  • Select an option

  • Save j-jayes/3f169d6fb5de1518ffd79c6bf22d2776 to your computer and use it in GitHub Desktop.

Select an option

Save j-jayes/3f169d6fb5de1518ffd79c6bf22d2776 to your computer and use it in GitHub Desktop.
Programmatically generate tabs in Rmarkdown with xaringanExtra
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = F, message = F, warning = F)
```
## Purpose
I need to create a number of tabs in an Rmarkdown document, depending on the contents of the data queried.
In short, the Rmarkdown document must have a tab for each factor in a dataset, and draw a ggplot in the tab.
I am using the fenced div structure to create tabsets from `xaringanExtra`.
```{r}
library(tidyverse)
library(xaringanExtra)
xaringanExtra::use_panelset()
df <- iris %>%
as_tibble() %>%
janitor::clean_names() %>%
filter(species != "setosa")
```
```{r}
theme_set(theme_light())
```
```{r}
make_panel <- function(spec) {
cat("::: {.panel}\n")
cat("##", spec, "{.panel-name}\n")
cat("Plot of", spec, "\n")
p <- df %>%
filter(species == spec) %>%
ggplot(aes(sepal_length, sepal_width, colour = petal_width)) +
geom_point()
print(p)
cat("\n")
cat(":::\n")
}
```
::::: {.panelset}
```{r, results='asis'}
species_tbl <- df %>% distinct(species)
for(i in species_tbl$species){
make_panel(i)
}
```
:::::
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment