Programmatically insert header and graph in the same code snippet with R markdown, using results = 'asis'

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 setosain 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?

+6
source share
1 answer

You need to add a few lines after the graphs and before the headings using cat('\n'):

```{r echo = FALSE, results ='asis'}
library(ggplot2)
for(Species in levels(iris$Species)){
  cat('\n#', Species, '\n')
  p <- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point()
  print(p)
  cat('\n')
}
+11
source

Source: https://habr.com/ru/post/1016949/


All Articles