R Markdown - 在循环中将文本格式设置为 header 似乎仅适用于第一次循环迭代

R Markdown - format text as a header in a loop seems to be working for 1st loop iteration only

我正在尝试使用从循环中动态生成的 headers 生成 R Markdown 文档。

我使用了来自类似 SO 问题的建议:, Using bold text in a loop for a Word document in Rmarkdown 并写了

---
title: "Untitled"
output:
  html_document:
    toc: true
    toc_depth: 5
---

## R Markdown

```{r, warning=FALSE, message=FALSE,  echo=FALSE}
library(ggplot2)
library(dplyr)
```

```{r fig.width=4, fig.height=2,  echo=FALSE, results='asis'}
experiment_names <- paste0("Experiment ", 1:3)

for (id in 1:3){ 

  cat("  \n")
  cat("### ",  experiment_names[id])
  cat("  \n")

  set.seed(id)
  plt <- 
    data.frame(x = rnorm(100)) %>%
    ggplot(aes(x = x)) + 
    geom_histogram(binwidth = 0.1)
  plot(plt)
}
```

但只有第一次循环迭代 header 被正确打印。如何让另外两个也工作?

我不知道为什么会这样,但试试一行而不是三行:

cat("\n\n### ", experiment_names[id], "\n")