Search code examples
rmarkdownrstudioknitr

Display .R script in output of .Rmd file


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.


Solution

  • 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'}
    ```