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.
One hacky solution I have found is to hardcode the html output directly in the documentation like this
## All results
```{r loopResults, echo=FALSE, results='asis'}
results = list(result1 = data.frame(x=rnorm(3), y=rnorm(3)), result2=data.frame(x=rnorm(3), y=rnorm(3)))
for(res in names(results)) {
cat(paste("<h3>Results for: ", res, "</h3>>"))
plot(results[[res]]$x, results[[res]]$y)
}
This doesn't seem to be the right way to do things, especially since I want to create PDF documents via pandoc at time and would have to change the hard-coded expressions. (I have currently convenience functions like h3(text, type)).
Is there a better way of doing this?
A possibility is to make your markdown file generate markdown instead of HTML. For example :
If you apply the
knit()
function to it in R, you will get the following Markdown file :And you should be able to use
pandoc
to produce HTML or LaTeX from this file ?Following https://gist.github.com/yihui/3145751 you can write a child template for inclusion and loop over that.
foosub.Rmd
foo.Rmd
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 hasinclude=FALSE
). All the formatted output is collected in theout
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:
which you cant.
I would use a combination of
brew
andknitr
to achieve this. I would create a brew template calleddoc.brew
which looks like thisYou can now run the following code to get your desired output
An alternative solution with pander:
And just
Pandoc.brew
this in one run to get what you were up to:Or generate HTML/docx/etc. in one run: