如何在R中使用knitr创建一个包含代码块和文本的循环 [英] how to create a loop that includes both a code chunk and text with knitr in R
问题描述
我试图弄清楚如何创建一个循环,该循环将一些文本插入到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的文本.
请注意:在\n
换行符前面需要两个空格,以使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 \n
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(" \n###", month.name[i], "Air Quaility \n")
#print(plot(airquality[airquality$Month == i,]))
plot(airquality[airquality$Month == i,])
cat(" \n")
}
```
这篇关于如何在R中使用knitr创建一个包含代码块和文本的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!