Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create RMarkdown chuncks in a loop

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?

like image 912
FMM Avatar asked Jun 18 '26 15:06

FMM


1 Answers

If you want to create headings + outputs within a loop, you can do:

```{r species_loop, results='asis'}
for(i in c("setosa", "versicolor", "virginica")) {

  cat(paste0("\n\n## ", i, "\n"))

  p <- df %>% 
    dplyr::filter(Species == i) %>% 
    ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) + 
    ggplot2::geom_point()
  print(p)
}
```

So:

  • Using results='asis' to allow output that you cat() to be interpreted as Markdown syntax
  • cat()ing the required markdown syntax to produce the headers (surrounded by some newlines to make sure it's interpreted properly)
  • Explicitly print()ing the plot within the loop.
like image 147
Marius Avatar answered Jun 20 '26 06:06

Marius