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?
The difference between running lines from a selection and invoking Source is that when running a selection all lines are inserted directly into the console whereas for Source the file is saved to a temporary location and then sourced into the console from there (thereby creating less clutter in the console).
source causes R to accept its input from the named file or URL or connection or expressions directly. Input is read and parse d from that file until the end of the file is reached, then the parsed expressions are evaluated sequentially in the chosen environment.
You can use the source function in R to reuse functions that you create in another R script. This function uses the following basic syntax: source("path/to/some/file.R") Simply add this line to the top of your R script and you'll be able to use any functions defined in file.
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
).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With