I would like to be able to create RMarkdown chuncks in a loop. I have tried doing this through a for
loop, without much success. I imagine this could probably be possible through lapply
, as one would do for creating UIs
in a shiny app. However, I haven't had any success so far.
Reprex:
---
title: "Untitled"
output:
html_document:
theme: united
highlight: tango
toc: true
toc_float:
collapsed: false
smooth_scroll: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```
```{r}
library(dplyr)
library(ggplot2)
df <- datasets::iris %>%
dplyr::as_tibble()
```
## setosa
```{r}
df %>%
dplyr::filter(Species == "setosa") %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
```
## versicolor
```{r}
df %>%
dplyr::filter(Species == "versicolor") %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
```
## virginica
```{r}
df %>%
dplyr::filter(Species == "virginica") %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
```
My goal is to create the headings (setosa, versicolor, and virginica) and the chuncks with a loop.
For example:
for(i in c("setosa", "versicolor", "virginica")) {
## i
df %>%
dplyr::filter(Species == i) %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
}
Any ideas on how accomplish this?