I am trying to generate an HTML report, using knitr, based on an R script that has for loops. I want to generate markdown comments from the comments within the for loop, but I am not sure if it's possible.
Here is simple example, this is in test.R:
for (i in 1:5) {
## This is a heading for `i`
#' This is a comment for `i`
print(i)
}
Then i use spin to generate a Rmd file: spin('test.R')
However, the Rmd file looks like the following.
```{r }
for (i in 1:5) {
## This is a heading for `i`
#' This is a comment for `i`
print(i)
}
```
The markdown comments within the R chunk are not compiled into HTML. Is it possible?
Thanks, Peter
I think you can obtain what you want in knitr with the code chunk option results='asis' that you can specify after "#+" in an R script to be passed to spin (but the code looks less "clean" than the interesting brew solution proposed by @daroczig):
If this is test.R script and that you do spin("test.R"), the resulting md file will look like that :
I have (re)implemented some features of
knitr
independently from @Yihui based onbrew
in my pander package that could help with such (and similar) issues if you do not want to runbrew
beforeknit
ting. Quick demo:Please note that you could also pass a file to
Pandoc.brew
(no need to use such troublesome setup with thetext
argument with real-life problems), and that you could also use<% ... %>
tags for e.g. conditionals (like showing or not rendering part of a report). And most importantly: there is a huge difference between<% ... %>
(unprocessed R commands) and<%= ... %>
(results are processed bypander
) tags. The latter means that all returned R objects are transformed to Pandoc's markdown, e.g.:One solution that worked for me, is provided by how to create a loop that includes both a code chunk and text with knitr in R. By using Both
results='asis'
and two spaces in front of\n
at the end of each loop.example:
Without two spaces:
Output (html):
As you can see, the comments and headings get messed together
Solution: With two spaces:
cat(" \n")
at the end of the loopnote:
cat(" \n")
needs to be at the very end, it does not work even if you plot or calculate something it in the loop.