RMarkdown中的“source"命令是什么?并显示现有 .R 文件中的代码? [英] What is the command in RMarkdown to "source" and display the code from an existing .R file?

查看:48
本文介绍了RMarkdown中的“source"命令是什么?并显示现有 .R 文件中的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:我的 R 脚本名为code.R".它生成了一个简单的 y 与 x 的关系图.在 Rmarkdown 中看起来像这样.

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)
    ```

为了文档和可重复性,我想创建一个 Rmarkdown 文件,该文件在从 RStudio 编织时读取code.R".(有点像 LaTex 中的 \include{}.)因此,生成的 RMarkdown PDF 应该显示来自code.R"的 R 代码的未经评估的逐字副本.

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".

最终目标是制作一个 RMarkdown 文件,该文件可读取数十个 R 文件并将所有 R 代码组合在一个 PDF 中,以供可重复性和未来参考.这将阻止我在每次更改源文件时复制粘贴新的 R 代码.我对在 RMarkdown 中实际运行 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?

````{r eval=FALSE} 中是否有现有的内置 RMarkdown 命令或附加选项可以产生我想要的结果?你能举个例子吗?

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?

一个更复杂的 Stackoverflow 问题的链接也间接解决了我的问题.

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

任何指针将不胜感激!

推荐答案

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

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

使用注释## ---- input.R"(不带引号)启动 input.R 脚本

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

使用以下代码制作一个 .Rmd 脚本并编织它.它将在生成的 PDF 中显示 input.R 脚本的内容.

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}

      ```

这篇关于RMarkdown中的“source"命令是什么?并显示现有 .R 文件中的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆