Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R, knitr, and source function: How to preserve source file comments for html report

Tags:

r

knitr

R console: When I call source("file_of_functions.R",echo=TRUE), all source file expressions, including comments, print to console.

Knit HTML: When I put source("file_of_functions.R",echo=TRUE) within a chunk and knit to html, the same output prints except for 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 f.R:

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

In console, the call source("f.R",echo=TRUE) prints:

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

When knitting to html, the call

```{r}
source("f.R",echo=TRUE)
```

yields the same output but without the comment.

like image 511
Jonathan Chipman Avatar asked Jun 30 '15 22:06

Jonathan Chipman


1 Answers

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

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

Personally I think this is much nicer than using source(), e.g. you don't get the prompts > by default (you can if you want), and the R code will be syntax highlighted. Of course, your comments will be preserved.

like image 146
Yihui Xie Avatar answered Sep 27 '22 20:09

Yihui Xie