我正在使用 RStudio。 我想在 for 循环内生成标题和绘图。但它不起作用。
我的代码应该生成三个标头。每个region_value 一个。但我只获取第一个区域值的标题。
我的代码有什么问题?
---
title: "Generate Headers"
format: html
editor: visual
---
## Generate dataframe
```{r}
#| echo: false
#| warning: false
library(tidyverse)
region = c(replicate(100,"A"),replicate(100,"B"),replicate(100,"C"))
variable = c(replicate(50,"var_a"),replicate(50,"var_b"),replicate(50,"var_a"),replicate(50,"var_b"),replicate(50,"var_a"),replicate(50,"var_b"))
value = runif(300, min = 0, max = 100)
df = data.frame(region = region, variable = variable, value = value)
```
# Plots
```{r}
#| echo: false
#| results: asis
regions_values <- unique(df$region)
for (region_value in regions_values){
cat("## ", region_value, "\n")
dfplot <- df |> filter(region == region_value)
p <- ggplot(dfplot, aes(x=variable, y=value)) + geom_boxplot()
print(p)
cat("\n")
}
```
在 Markdown 中,您需要在
##
行之前添加一个新行,以便将其解释为标题。将第二个块更改为:
#| echo: false
#| results: asis
regions_values <- unique(df$region)
for (region_value in regions_values){
cat("## ", region_value, "\n")
dfplot <- df |> filter(region == region_value)
p <- ggplot(dfplot, aes(x=variable, y=value)) + geom_boxplot()
print(p)
cat("\n\n")
}
这将产生三个标题: