如何将R脚本粘贴在一起以生成一个笔记本?

问题描述

我有几个R脚本,例如a.Rb.Rc.R。我想将所有脚本粘贴到一个文件中,然后使用该文件生成笔记本。

a.R中,代码

#' This is some text in a.R to be used in Notebook.
dat1 <- 1:10

b.R中,代码

#' This is some text in b.R to be used in Notebook.
dat2 <- dat1

c.R中,代码

#' This is some text in c.R to be used in Notebook.
dat3 <- dat2

我想要一个整体文件all.R,它应该看起来像这样:

#' This is some text in a.R to be used in Notebook.
dat1 <- 1:10
#' This is some text in b.R to be used in Notebook.
dat2 <- dat1
#' This is some text in c.R to be used in Notebook.
dat3 <- dat2

我也可以手动将所有内容复制到一起,但是我不想这样做,因为我会丢失所有内容的概述。我想知道是否还有其他更优雅的方式?

解决方法

您可以使用child knitr chunck选项:

---
title: "Notebook"
output: html_document
---

```{r insertScriptA,child = 'ScriptA.Rmd'}
```

```{r insertScriptB,child = 'ScriptB.Rmd'}
```
,

我找到了自己使用的解决方案。

我使用系统命令将每个R脚本连接到另一个R脚本all.R,然后将all.R转换为all.Rmd。我使用的是Linux。

这是我仅在R中做过的事情:

library(knitr)
#cat is a command under linux to concatenate files. The first command is used to generate all.R.
system("cat a.R b.R c.R > all.R") 
spin("all.R") # Convert all.R to all.Rmd