I was reading similar questions (here, here, and here and also here) but haven't been able to get this working, possibly due to a mix of grobs and rastergrobs in the list within the loop. Essentially, I have a nested for loop to print objects in a list, and want headers for the objects using markdown. I'm going with the knit_expand approach with child templates. If I set results='asis' the headers work but the plots don't, and if I remove results='asis' the plots work but not the headers. Any solutions? Here is a reproducible example that is close to what I'm doing though the sublists are contrived here and not working exactly correct but the idea is the same (a mix of headers that need to be asis and plot objects):
Master template (Master.Rmd)
---
title: "Example"
output:
html_document:
toc: true
toc_float: true
toc_depth: 2
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(datasets)
library(ggplot2)
library(data.table)
library(png)
library(grid)
library(gridExtra)
library(RCurl)
data(iris)
plotsList = vector(mode = "list", length = length(levels(iris$Species)))
names(plotsList) = levels(iris$Species)
irisDT = as.data.table(iris)
dataInList = split(irisDT, by="Species")
for(i in seq(plotsList)){
plotsList[[i]]$example_plot[1] <- list(ggplot(data=dataInList[[i]], aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() + xlab("Sepal Length") + ylab("Sepal Width") +
ggtitle(paste0("Sepal Length-Width for ", names(plotsList[i]))))
plotsList[[i]]$example_plot[2] <- list(ggplot(data=dataInList[[i]], aes(x = Petal.Length, y = Petal.Width)) +
geom_point() + xlab("Petal Length") + ylab("Petal Width") +
ggtitle(paste0("Petal Length-Width for ", names(plotsList[i]))))
plotsList[[i]]$png_example <- rasterGrob(readPNG(getURLContent(("https://i.imgur.com/mfuTUPD.png"))))
}
```
# Big Heading
some text
## Other headings
other text
# Loop output Description {.tabset .tabset-fade}
text about loop output
```{r run_loop, echo=FALSE}
# for the headings to work, results need to be asis, but then the plots don't work :(
out = NULL
out2 = NULL
for(i in seq(plotsList)){
cat("\n")
cat("## ", {{names(plotsList[i])}}, "\n")
out = c(out, knit_expand('one_level.Rmd'))
for(j in seq(plotsList[[i]][['example_plot']])){
out2 = c(out2, knit_expand('two_level.Rmd'))
}
}
```
`r paste(knit(text = out), collapse = '\n')`
`r paste(knit(text = out2), collapse = '\n')`
```
and the child template (Child.Rmd):
```{r echo=FALSE}
grid.arrange(plotsList[[i]][['example_plot']][[j]])
```
```{r echo=FALSE, results='asis'}
grid.arrange(plotsList[[i]][['png_example']])
```