0

Is it possible to run multiple .R files from the shell or a bash script, in sequence, in the same R session (so without having to write intermediate results to disk)?

E.g. if file1.R contains a=1 and file2.R print(a+1)

then do something like

$ Rscript file1.R file2.R
[1] 2

(of course a workaround would be to stitch the scripts together or have a master script sourcing 1 and 2)

3
  • you have the bash as a tag, why don't you make a multine bash code then ? Commented Oct 5, 2020 at 8:51
  • a bash script calling Rscript twice will also instantiate two R sessions, and return " 'a' not found" in the second one. Commented Oct 5, 2020 at 8:59
  • oh - then you need to make a wrapper with 'source' command - sb made an answer Commented Oct 5, 2020 at 9:06

2 Answers 2

1

You could write a wrapper script that calls each script in turn:

source("file1.R")
source("file2.R")

Call this source_files.R and then run Rscript source_files.R. Of course, with something this simple you can also just pass the statements on the command line:

Rscript -e 'source("file1.R"); source("file2.R")'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, yes this was my 'master script' workaround. Was wondering if there was a way of avoiding it, but it's definitely a way.
0

The accepted answer really helped me, thank you!

In poking around the documentation, I also discovered that Rscript also takes multiple expressions, provided each expression is preceded by the "-e" flag.

So, this would also work:

Rscript -e "source('file1.R')" -e "source('file2.R')" [args]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.