问题描述
我想弄清楚如何创建一个循环,将一些文本插入到 rmarkdown 文件中,然后生成与该标题对应的图形或表格.以下是我想象它的工作方式:
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:
for(i in 1:max(month)){
### `r month.name[i]` Air quaility
```{r, echo=FALSE}
plot(airquality[airquality$Month == 5,])
```
}
这当然只是将 for 循环打印为文本,如果我用 r`` 包围 for 循环,我只会得到一个错误.
This ofcourse just prints the for loop as text, if i surround the for loop with r`` I would just get an error.
我希望代码生成一个如下所示的 rmd 文件:
I want the code to produce an rmd file that looks like this:
剧情
剧情
等等等等.有任何想法吗?我不能使用乳胶,因为我在工作时他们不让我们下载 exe 文件,而且我也不知道如何使用乳胶.我想制作一个word文档.
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.
推荐答案
您可以使用 cat()
将 Markdown 嵌入循环中.
You can embed the markdown inside the loop using cat()
.
注意:您需要设置 results="asis"
以将文本呈现为 Markdown.请注意:您将需要在 新行字符前面有两个空格才能让 knitr 在有情节的情况下正确呈现降价.
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 new line character to get knitr to properly render the markdown in the presence of a plot out.
# Monthly Air Quality Graphs
```{r pressure,fig.width=6,echo=FALSE,message=FALSE,results="asis"}
attach(airquality)
for(i in unique(Month)) {
cat("
###", month.name[i], "Air Quaility
")
#print(plot(airquality[airquality$Month == i,]))
plot(airquality[airquality$Month == i,])
cat("
")
}
```
这篇关于如何在 R 中使用 knitr 创建一个包含代码块和文本的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!