The results = 'asis'
chunk option in Rmarkdown makes it easy to dynamically create text, including headings. However, I want to dynamically create a header with a parameter asis
, but then insert some graphics in the same code snippet.
The most related answer that I could find for this is here: Programmatically insert text, headings and lists marked R , but the answer to this question does not allow both dynamic headers and graphics in these dynamic headers.
The following is a simple reproducibility example demonstrating what I can and cannot achieve with results = 'asis'
The code directly below does what I expect, creating a title for each view.
---
output: html_document
---
```{r echo = FALSE, results ='asis'}
for(Species in levels(iris$Species)){
cat('#', Species, '\n')
}
```
The code below does not do what I would like. Ideally, the code immediately below will generate a heading for each view with a graph below each heading. Instead, it generates a single header setosa
in the output file, followed by three graphs.
---
output: html_document
---
```{r echo = FALSE, results ='asis'}
library(ggplot2)
for(Species in levels(iris$Species)){
cat('#', Species, '\n')
p <- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
print(p)
}
```
Is there a way to dynamically generate 3 headings with a graph under each heading?