3

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.

user140571
  • 31
  • 2
  • Relevant: https://github.com/yihui/knitr/issues/408#issuecomment-247157358 and https://github.com/r-lib/evaluate/issues/14 and https://stackoverflow.com/q/11956520/7162131 – henrik_ibsen Jun 06 '19 at 07:08
  • https://stackoverflow.com/questions/61330051 – Brian D Oct 07 '22 at 21:26

0 Answers0