I want to iterate over a list of result-sets in my R markdown file. When I produce the output I want to include some text like headers with the name of the result set.
Following https://gist.github.com/yihui/3145751 you can write a child template for inclusion and loop over that.
foosub.Rmd
Results for `r res`
---------------------------
```{r}
plot(results[[res]]$x, results[[res]]$y)
```
foo.Rmd
```{r loopResults, include=FALSE}
results = list(result1 = data.frame(x=rnorm(3), y=rnorm(3)), result2=data.frame(x=rnorm(3), y=rnorm(3)))
out=NULL
for(i in 1:length(results)) {
res = names(results)[i]
out = c(out, knit_child('foosub.Rmd', sprintf('foosub-%d.txt', i)))
}
```
`r paste(out, collapse = '\n')`
The code chunk in the master file doesn't produce any output itself, it just renders the child documents, one for each of your results, and stores it all up in out (which is why it has include=FALSE). All the formatted output is collected in the out variable and inserted by the last line.
Its a bit awkward, but it does encourage modularity, but it doesn't seem as simple as being able to do:
```{r}
for(i in 1:10){
```
Plot `r i`
-----------
```{r}
plot(1:i)
}
```
which you cant.