Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include code from an external R script, run in, display both code and output

Is it possible to include code from an external R script in an .Rmd and simultaneously run the code, display the code, and display its results in the output .HTML file? For example, if I have

x <- 1 y <- 3 z <- x + y z 

in external.R. In the output document I want to see the code above along with the result of z, i.e. 4. Essentially, I want the equivalent of what would happen if I copy/pasted what's above in an R chunk. So I want

```{r} some.library::some.function("external.R") ``` 

to be the equivalent of

```{r} x <- 1 y <- 3 z <- x + y z ``` 

In the output HTML file. I've tried things like knitr::read_chunk('external.R) and source('external.R)`, but these don't display the code. Am I missing something simple?


EDIT

I found that source('external.R', echo = TRUE) will produce what I ask, but each line of the output's displayed code/results is prepended by ##. Any way to make it look like it would if the code was simply copy/pasted in a chunk in the .Rmd?

like image 536
haff Avatar asked Sep 19 '18 03:09

haff


People also ask

How do I run an R script from another R script?

You can execute R script as you would normally do by using the Windows command line. If your R version is different, then change the path to Rscript.exe. Use double quotes if the file path contains space.

How do I display output but not code in R?

You use results="hide" to hide the results/output (but here the code would still be displayed). You use include=FALSE to have the chunk evaluated, but neither the code nor its output displayed.

How do I show code output in R Markdown?

If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .

How do I embed code in R Markdown?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).


Video Answer


2 Answers

Although the accepted answer provides a simple and working solution, I think the most idiomatic way of doing this (without having to modify the external script at all) is to use the chunk option code to set the contents of external.R as chunk code:

```{r, code = readLines("external.R")} ``` 
like image 182
CL. Avatar answered Sep 29 '22 10:09

CL.


There is another way of doing it so it looks exactly like having the code in the markdown file.

Your external.R file:

## @knitr answer x <- 1 y <- 3 z <- x + y z 

Your Rmarkdown file:

--- title: "Untitled" output: html_document ---  ```{r echo=FALSE} knitr::read_chunk('external.R') ```  ```{r} <<answer>> ``` 

That produces: enter image description here

like image 27
spadarian Avatar answered Sep 29 '22 10:09

spadarian