How to paste R script together to generate one Notebook?

102 views Asked by At

I have several R scripts, say a.R, b.R, c.R. I want to paste all scripts together to one file and then use this file to generate a Notebook.

In a.R, the code is

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

In b.R, the code is

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

In c.R, the code is

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

I want to have an overall file all.R and it should look like this:

#' 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

I could also manuelly copy everything together, but I do not want to because I will lose an overview of everything. I am wondering whether there is any more elegent way?

2

There are 2 answers

1
Waldi On

You could use child knitr chunck option:

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

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

```{r insertScriptB, child = 'ScriptB.Rmd'}
```
0
Qi Yin On

I found a solution for my own use.

I use a system command to concatenate every R scripts together to another R script all.R and then I convert all.R to all.Rmd. I use linux.

Here is how I did it in R only:

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