在四开中循环生成段落

问题描述 投票:0回答:1

我想用 R / Quarto 生成一个 Word 文档 (docx),其中在一个项目内,我有通过循环创建的子项目。我使用的是 R 版本 4.2.2、R Studio 2022.12.0 Build 353、Quarto 1.2.280 和 Ubuntu 20.04。

例如,在介绍性文本给出主题概述之后,我想生成包含每个项目详细信息的子项目。

如果没有循环,代码将是:

---
title: "Data by County"
format:
  docx:
    number-sections: true
---

```{r}
#| echo=FALSE,
#| include=FALSE

dat.county <- data.frame(
  county = LETTERS[1:5],
  pop_num = round(runif(5,100,500)),
  gdp = runif(5,1000,5000)
)
```

# Identifying county characteristics

A total of `r nrow(dat.county)` counties, with a total population of `r sum(dat.county$pop_num)` thousand people were characterized as follows:

## County `r dat.county[1,1]`

County `r dat.county[1,1]` has a population of `r dat.county[1,2]` thousand people with a real gross domestic product of `r dat.county[1,3]`.

## County `r dat.county[2,1]`

County `r dat.county[2,1]` has a population of `r dat.county[2,2]` thousand people with a real gross domestic product of `r dat.county[2,3]`.

等等。

我尝试插入如下所示的循环,但没有成功。 “##”不被识别为标题。我还遇到了换行符和段落的问题。最后,使用cat的代码并不像上面的文字那么优雅。

```{r}
#| echo=FALSE

  for (i in 1:nrow(dat.county)) {
  
  cat("## County",dat.county[i,1],"\n")
  
  cat("County ",dat.county[i,1]," has a population of ",dat.county[i,2]," thousand people with a real gross domestic product of ",dat.county[i,3],"\n")
  }
```

我的问题是,我怎样才能生成类似的东西

## County `r dat.county[i,1]`

County `r dat.county[i,1]` has a population of `r dat.county[i,2]` thousand people with a real gross domestic product of `r dat.county[i,3]`

在循环内?

r r-markdown rstudio knitr quarto
1个回答
7
投票

您只需要添加块选项

results='asis'
并在调用时使用双换行符
cat()
:

---
title: "Data by County"
format:
  docx:
    number-sections: true
---


```{r}
#| echo: false
#| include: false

dat.county <- data.frame(
  county = LETTERS[1:5],
  pop_num = round(runif(5,100,500)),
  gdp = runif(5,1000,5000)
)
```

```{r}
#| echo: false
#| results: 'asis'

  for (i in 1:nrow(dat.county)) {
  
  cat("## County",dat.county[i,1],"\n\n")
  
  cat("County ",dat.county[i,1]," has a population of ",dat.county[i,2]," thousand people with a real gross domestic product of ",dat.county[i,3],"\n\n")
  }
```

给予:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.