Ramnath
Ramnath

Reputation: 55725

Rscript vs. source: What are the key differences?

This might be a very basic question, but have not found a convincing answer yet. When executing an R script within the R environment, I can either do source(foo.R) or system("Rscript foo.R"). Is there any difference at all between the two approaches, and if so how do the two approaches compare?

Upvotes: 18

Views: 3334

Answers (3)

Josh O'Brien
Josh O'Brien

Reputation: 162421

They're fundamentally different in their effects.

  • source("foo.R") tells your current R process to take its input from "foo.R".

  • system("Rscript foo.R") uses an operating system command to launch a separate R process, within which the contents of "foo.R" are evaluated.

The Rscript call won't directly affect your current R session at all, except that it will by default print the output of that other R session on your current console. (You can disable this in your system() call by setting show.output.on.console=FALSE).

Upvotes: 16

Hong Ooi
Hong Ooi

Reputation: 57696

As an answer to @Ramnath's comment: sys.source("foo") is not the same as Rscript foo. For example, you can do the following with sys.source:

e <- new.env()
sys.source("foo", e)  # foo creates a bunch of objects in environment e
z <- with(e, {
    # do stuff with e....
})
rm(e)

You might do this if you are creating several intermediate objects, which you then do stuff on and return a final result. You don't want to keep the intermediate objects, so putting them into their own temporary environment is an easy way to remove them in one go.

Upvotes: 2

Blender
Blender

Reputation: 298432

I think source(foo.R) includes the source code of that file (foo.R) into your current environment. If you define a variable within foo.R, let's say x <- 5, and in your current project you define x <- 6 beforehand, x becomes 5.

system("Rscript foo.R") runs the Rscript program with the argument foo.R, so your current environment is not affected at all.

Upvotes: 3

Related Questions