Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the command in RMarkdown to "source" and display the code from an existing .R file?

Tags:

r

r-markdown

Example: My R script is named "code.R". It produces a simple plot of y versus x. And looks like this in Rmarkdown.

    ````{r eval=FALSE}
    ## code in "code.R"
    x = 1:10
    y = 1:10
    plot(x,y)
    ```

For documentation and reproducibility I want to create a Rmarkdown file which reads "code.R" when knitted from RStudio. (A bit like \include{} in LaTex.) The resulting RMarkdown PDF should thus display a not-evaluated verbatim copy of the R code from "code.R".

The end goal is to make a RMarkdown file which reads dozens of R-files and groups all R-code in one PDF for reproducibility and future reference. This would prevent me to copy-paste the new R code each time I alter the source files. I am not interested in actually running the R-code in RMarkdown.

Part of a solution (but how?) might be to create a chunk which read the file and stores the read textlines and another chunk which displays these text lines as verbatim code?

Is there an existing build-in RMarkdown command or additional options in ````{r eval=FALSE} which produce my intended result? Could you provide an example?

A link to a more complicated Stackoverflow question which addresses my problem indirectly is also appreciated.

Any pointers would be appreciated!!

like image 569
Daniel Avatar asked Jun 08 '15 10:06

Daniel


1 Answers

Solution found on: http://yihui.name/knitr/demo/externalization/

Start your input.R script with the comment "## ---- input.R" (without the quotes)

Make an .Rmd script with the following code and Knit it. It will show the content of the input.R script in the resulting PDF.

      ---
      output: pdf_document
      ---

      ```{r cache=FALSE, echo=FALSE}
      knitr::read_chunk('input.R')
      ```

      ```{r input.R, eval=FALSE}

      ```
like image 151
Daniel Avatar answered Oct 22 '22 12:10

Daniel