Generating plots in R markdown via a for loop over a list

I want to generate multiple plots in an R markdown document as tabbed content in an automated way. I tried to use a for loop as solution for looping over multiple years in my data. The code works fine as simple R code and generates the various plots, but does not work as R markdown code.

This is the central part of the code with the for loop:

### Section {.tabset .tabset-fade}

```{r mydata, echo = F, results = 'asis'}
#data transformation
mydata_year <- split(mydata, mydata$year)

mydata_faculty <- lapply(mydata_year, group_by_faculty)

#for loop generating plots
for (i in 1:length(mydata_faculty)) {
  cat("#### ", names(mydata_faculty)[[i]], "\n")
  print(paste("The year is", names(mydata_faculty)[[i]]))
  myplot <- draw_chart_bar(mydata_faculty[[i]]) %>%
    hc_title(text = paste("Year", names(mydata_faculty)[[i]]))
  cat("\n")
  print(myplot)
  cat("\n")
  }

```

### {.toc-ignore}

This is the whole setup (data, functions etc.):

---
title: "Test"
output:
  html_document
---

```{r setup, include=FALSE}
library(tidyverse)
library(highcharter)

#data
mydata <- structure(list(
  year = c(2020L, 2020L, 2020L, 2021L, 2021L, 2021L),
  faculty = c("medicine", "medicine", "physics", "chemistry", "medicine", "medicine"),
  cost = c(1500L, 1700L, 1300L, 1700L, 2000L, 2000L)), class = "data.frame", row.names = c(NA, -6L)
)

#function for data transformation
group_by_faculty <- function(x) {
  x %>% group_by(faculty)
}

#function for drawing bar chart
draw_chart_bar <- function(x) {
  hchart(x,"column",
    hcaes(x = faculty, y = cost)
  )
}
```

### Section {.tabset .tabset-fade}

```{r mydata, echo = F, results = 'asis'}
#data transformation
mydata_year <- split(mydata, mydata$year)

mydata_faculty <- lapply(mydata_year, group_by_faculty)

#for loop generating plots
for (i in 1:length(mydata_faculty)) {
  cat("#### ", names(mydata_faculty)[[i]], "\n")
  print(paste("The year is", names(mydata_faculty)[[i]]))
  myplot <- draw_chart_bar(mydata_faculty[[i]]) %>%
    hc_title(text = paste("Year", names(mydata_faculty)[[i]]))
  cat("\n")
  print(myplot)
  cat("\n")
  }

```

### {.toc-ignore}

What am I missing here?

To achieve that, please follow the example and recipies fro mthe cookbook
Yes knit_child() is a good solution.

If you want to go further, have a look in the R Markdown cookbook. There are seveal chapter with recipes to help with such task. You'll find some examples about generating rmarkdown content from code with lapply(), knit_child() and knit_expand() also. Using those tools is the best way to have knitr handling correctly your output.

Also this is a usual question, so you should find example of this out there too, probably in this forum for severa l use case.

Why your try does not work as expected

Mixing cat() and print() with text and plot in a asis chunk won't correctly make the plot be handled by knitting process. FWIW knitr uses knit_print() to generate the correct output to embed and not print(). Using knit_child() to render a content to insert in another is the best way to make this happen.

Hope it helps

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.