Looping headers/sections in rmarkdown?

非 Y 不嫁゛ 提交于 2020-04-13 17:48:20

问题


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.

来源:https://stackoverflow.com/questions/56468804/looping-headers-sections-in-rmarkdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!