Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

r - generate markdown comments within for loop

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, "
")
    cat("<!-- This is a comment for ", i, "-->
")
    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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...