5

Is it possible to include or display an .r script in the output of .rmd file?
Important - just want to display the .r file! Tried source(filename.r); source does not display it. Any ideas?

**knitr Global Options**   

```{r echo=TRUE}
knitr::opts_chunk$set(tidy=FALSE, fig.path='figures/')
```

**Load Libraries**   

```{r echo=TRUE}
library(dplyr)
```

```{r echo=TRUE, include=TRUE}
source("external.R")
# the complete source code of the .r file should be displayed here
# possible?
```

What would be the use-case for such a requirement?
Creating .Rmd helps with documentation. In fact all my documentation is created using .Rmd.
There are .R scripts which take a long time to run (processing large data). In such a case working with .Rmd is not practical. Prefer to work with .R scripts.
If the source code of the .R can be "included & displayed" in the .Rmd would be wonderful for documentation purpose.

Cyrus Lentin
  • 163
  • 1
  • 7

1 Answers1

13

For this particular case, there is a simple solution. That is, you can assign source code to the chunk option code, then knitr will just take your source code as if it were written in the code chunk, e.g.

```{r, code = readLines('external.R')}
```

Alternatively and equivalently, you can use the file option:

```{r, file = 'external.R'}
```
Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • 2
    Nice. I should've known to just wait until you came along with the perfectly elegant solution :) – Josh O'Brien Apr 20 '15 at 23:27
  • @JoshO'Brien Oh no, please keep up your momentum :) Thanks! I'm answering this one just because it is not a widely known feature, and I was glad that I found a use case. – Yihui Xie Apr 20 '15 at 23:47
  • 2
    @WaldirLeoncio That is just a basic subsetting question. You can `readLines('external.R')[c(lines, you, want, to, use)]`. – Yihui Xie Jul 09 '15 at 18:40
  • Yihui, does this solution only prints the script code or does it execute it as well? I've been getting some strange issues here. – Waldir Leoncio Jul 10 '15 at 15:39
  • You can choose to execute it or not by `eval = TRUE` or `FALSE`. – Yihui Xie Jul 10 '15 at 20:18
  • Been a while since this was posted. Is there a way to automate this in Rmd when I want to output a few different scripts? As in, I want to define a function to print the two lines of code here, where the only thing that changes is the filename. – kputschko Feb 22 '22 at 19:14