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

谁都会走 提交于 2020-05-08 09:07:06

问题


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!!


回答1:


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}

      ```


来源:https://stackoverflow.com/questions/30706967/what-is-the-command-in-rmarkdown-to-source-and-display-the-code-from-an-existi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!