Reputation: 535
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,])
```
}
This ofcourse just prints the for loop as text, if i surround the for loop with r`` I would just get an error.
I want the code to produce an rmd file that looks like this:
Plot
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.
Upvotes: 50
Views: 26703
Reputation: 182
What about reusing the chunks inside a loop using <<label>> as described here: https://bookdown.org/yihui/rmarkdown-cookbook/reuse-chunks.html
Label your chunk, set eval=F
```{r my_chunk, echo=FALSE, eval=F}
plot(airquality[airquality$Month == 5,])
```
Then loop
for(i in 1:max(month)){
<<my_chunk>>
}
Upvotes: 4
Reputation: 288
Under some conditions I find it helpful to write a loop that writes chunk code rather than write a chunk that runs a loop. Weird solution but it has worked for me beautifully in the past when a bare bones set of chunks is all I need. For your airquality
case it would look like this:
## model chunk ##
# ## May Air Quality
# ```{r May}
#
# plot(airquality[airquality$Month == 5,])
#
# ```
# all months in airquality
aqmonths <- c("May",
"June",
"July",
"August",
"September")
for (m in aqmonths) {
cat(
paste0(
"## ", m, " Air Quality",
"\n\n",
"```{r ", m, "}",
"\n\n",
"plot(airquality[airquality$Month == ", match(m, months), ",])",
"\n\n",
"```",
"\n\n"
)
)
}
This will print code for all 5 chunks to the console, and then I can copy and paste into a .Rmd document. It is possible to include any chunk options such as captions or fig
arguments in the chunk-writing loop as well. Depending on what else you try to bring in, using functions like match()
as in the example is often helpful.
Pros: Preserves ability to use cross-references and set individual captions or options.
Cons: Making changes to all chunks usually requires re-copying the entire output of the chunk-writing loop, which can be tiresome and a bit unwieldy.
Upvotes: 2
Reputation: 3973
As mentioned here, you could also make use of the pander package:
# Monthly Air Quality Graphs
```{r pressure2, fig.width=6, echo=FALSE, message=FALSE, results="asis"}
library(pander)
for (i in unique(airquality$Month)) {
# Inserts Month titles
pander::pandoc.header(month.name[i], level = 3)
# Section contents
plot(airquality[airquality$Month == i,])
# adding also empty lines, to be sure that this is valid Markdown
pander::pandoc.p('')
pander::pandoc.p('')
}
```
Upvotes: 12
Reputation: 2339
You can embed the markdown inside the loop using cat()
.
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")
}
```
Upvotes: 75