如何在R中创建一个包含代码块和带有knitr的文本的循环

时间:2022-12-29 06:13:45

I am trying to figure out how to create a loop that inserts some text into the rmarkdown file, and then produces the graph or table that corresponds to that header. The following is how I picture it working:

我试图弄清楚如何创建一个循环,将一些文本插入到rmarkdown文件中,然后生成与该标题对应的图形或表格。以下是我的工作原理:

for(i in 1:max(month)){
### `r month.name[i]` Air quaility

```{r, echo=FALSE}
plot(airquality[airquality$Month == 5,])
```
}

This ofcourse just prints the for loop as text, if i surround the for loop with r`` I would just get an error.

这个当然只是打印for循环作为文本,如果我用r``环绕for循环我只会得到一个错误。

I want the code to produce an rmd file that looks like this:

我希望代码生成一个如下所示的rmd文件:

May Air Quality

Plot

情节

June Air Quality

plot

情节

and so on and so forth. any ideas? I cannot use latex because I at my work they do not let us download exe files, and I do not know how to use latex anyways. I want to produce a word document.

等等等等。有任何想法吗?我不能使用乳胶,因为我在工作时不会让我们下载exe文件,而且我不知道如何使用乳胶。我想制作一个word文档。

1 个解决方案

#1


20  

You can embed the markdown inside the loop using cat().

您可以使用cat()将markdown嵌入循环中。

Note: you will need to set results="asis" for the text to be rendered as markdown. Note well: you will need two spaces in front of the \n new line character to get knitr to properly render the markdown in the presence of a plot out.

注意:您需要为要呈现为markdown的文本设置results =“asis”。注意:你需要在\ n新行字符前面有两个空格才能让knitr在出现情节时正确渲染降价。

# Monthly Air Quality Graphs
```{r pressure,fig.width=6,echo=FALSE,message=FALSE,results="asis"}

attach(airquality)
for(i in unique(Month)) {
  cat("  \n###",  month.name[i], "Air Quaility  \n")
  #print(plot(airquality[airquality$Month == i,]))
  plot(airquality[airquality$Month == i,])
  cat("  \n")
}
```

#1


20  

You can embed the markdown inside the loop using cat().

您可以使用cat()将markdown嵌入循环中。

Note: you will need to set results="asis" for the text to be rendered as markdown. Note well: you will need two spaces in front of the \n new line character to get knitr to properly render the markdown in the presence of a plot out.

注意:您需要为要呈现为markdown的文本设置results =“asis”。注意:你需要在\ n新行字符前面有两个空格才能让knitr在出现情节时正确渲染降价。

# Monthly Air Quality Graphs
```{r pressure,fig.width=6,echo=FALSE,message=FALSE,results="asis"}

attach(airquality)
for(i in unique(Month)) {
  cat("  \n###",  month.name[i], "Air Quaility  \n")
  #print(plot(airquality[airquality$Month == i,]))
  plot(airquality[airquality$Month == i,])
  cat("  \n")
}
```