Looping headers/sections in rmarkdown?

Viewed 423

I am trying to generate a loop with sections/headers that are followed by a figure in rmarkdown. I understand that I can use cat("## xyz") to generate a new header in my chunk but I observe some odd behaviour.

---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = F)
```

Version 1: (does not work)

```{r, results='asis'}
for (i in 1:5) {
  cat("\n")  
  cat("## This is a heading for ", i, "\n")

    plot(pressure)
    cat("\n")  

}
```

Version 2: (does not work)

```{r, results='asis'}
for (i in 1:5) {
  cat("\n")  
  cat("## This is a heading for ", i, "\n")

    plot(pressure)
    cat("\n")  

    plot(pressure)
    cat("\n")  

}
```

Version 3 (works):
```{r, results='asis'}
for (i in 1:5) {
  cat("\n")  
  cat("## This is a heading for ", i, "\n")

  plot(cars)
  cat("\n")  

  plot(pressure)
  cat("\n")   
}
```

I expect the output to be

Header 1

Figure 1

Header 2

Figure 2

Header 3

Figure 3

etc.

0 Answers
Related