Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 696
Cyrus Lentin Avatar asked Apr 20 '15 21:04

Cyrus Lentin


People also ask

How do I display code output in R Markdown?

There are two ways to render an R Markdown document into its final output format. If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it. Note that both methods use the same mechanism; RStudio's “Knit” button calls rmarkdown::render() under the hood.

How do I convert a RMD file to R?

If you use the RStudio IDE, the keyboard shortcut to render R scripts is the same as when you knit Rmd documents ( Ctrl / Cmd + Shift + K ). When rendering an R script to a report, the function knitr::spin() is called to convert the R script to an Rmd file first.

How do I show a script in R?

You create new R Script by clicking on File > New File > R Script in the RStudio menu bar. To execute your code in the R script, you can either highlight the code and click on Run, or you can highlight the code and press CTRL + Enter on your keyboard.

Is code that can be inserted directly into a .RMD file?

Code results can be inserted directly into the text of a . Rmd file by enclosing the code with `r ` .


1 Answers

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'}
```
like image 161
Yihui Xie Avatar answered Sep 20 '22 14:09

Yihui Xie