首页 > 解决方案 > 在 rmarkdown 中循环标题/部分?

问题描述

我正在尝试生成一个带有部分/标题的循环,后面跟着一个 rmarkdown 中的数字。我知道我可以使用 cat("## xyz") 在我的块中生成一个新标头,但我观察到一些奇怪的行为。

---
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")   
}
```

我希望输出是

标题 1

图1

标题 2

图 2

标题 3

图 3

等等

标签: r-markdown

解决方案


推荐阅读