generate markdown comments within for loop

pmichaels picture pmichaels · Jun 18, 2013 · Viewed 13.9k times · Source

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

Answer

Gilles picture Gilles · Jun 19, 2013

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):

#+ results='asis', echo = FALSE
for (i in 1:5) {
    cat("## This is a heading for ", i, "\n")
    cat("<!-- This is a comment for ", i, "-->\n")
    print(i)    
}

If this is test.R script and that you do spin("test.R"), the resulting md file will look like that :

## This is a heading for  1 
<!-- This is a comment for  1 -->
[1] 1
## This is a heading for  2 
<!-- This is a comment for  2 -->
[1] 2
## This is a heading for  3 
<!-- This is a comment for  3 -->
[1] 3
## This is a heading for  4 
<!-- This is a comment for  4 -->
[1] 4
## This is a heading for  5 
<!-- This is a comment for  5 -->
[1] 5