R, knitr and source: how to save source file comments for html report

Console R: When I call source("file_of_functions.R",echo=TRUE) , all expressions of the source file, including comments, are output to the console.

Knit HTML: When I put source("file_of_functions.R",echo=TRUE) in a piece and knit in html, the same output is output with the exception of comments.

For clarity of my code and report, I would like the comments of the source file to be included in the html report.

Any suggestions?

Basic example: Save the following as fR:

 # function to add a number to itself f <- function(x) x+x f(2) 

In the console, a call to source("fR",echo=TRUE) prints:

 #function to add a number to itself > f <- function(x) x+x > f(2) > [1] 4 

When knitting in html call

 ```{r} source("fR",echo=TRUE) ``` 

gives the same result, but without comment.

+8
r knitr
source share
2 answers

test.Rmd

 --- output: html_document --- ```{r} options(prompt = '> ') ``` ```{r} source('./test.r', echo = TRUE) ``` ```{r} source('./test.r', echo = TRUE, keep.source = TRUE) ``` 

enter image description here

+4
source share

I don't want to post this as an answer, but I just want to point out that you can easily insert test.r into a piece of code using

 ```{r code=readLines('test.r')} ``` 

Personally, I think this is much better than using source() , for example. you don’t get hints > by default (you can if you want), and the R-code will be highlighted with syntax. Of course, your comments will be saved.

+9
source share

All Articles