In a newer version of R,
Rscript
or Rscript.exe
is a command mode of R
without a terminal and can be used as a shell script.
It also provides a more convenient interface than traditional ways as
SHELL> R --vanilla < a_rscript.r
or
SHELL> R CMD BATCH --vanilla a_rscript.r
or in Windows System,
SHELL> R.exe --vanilla < a_script.r
and
SHELL> Rcmd.exe BATCH --vanilla < a_script.r
or
SHELL> R.exe CMD BATCH --vanilla a_script.r
where "a_script.r" is an R script file.
Rscript
is also especially useful for taking in arguments from STDIN, and it is
easily utilized by other script language.
In particular, it can be a shell script as shown in the Example 1 below.
For parallel computing, "Rscript" provides an elegant way to perform
a common programming design,
Single Program Multiple Data (SPMD).
More examples about batch jobs can be found at
the section
"Batch jobs"
and
"Batch more"
on the
R_note
website.
Example 1:
Hello world !
In a Unix, one can put the following in a file "an_rscript.r", then execute as scripts in perl, php, python or any other shell scripts.
#!/usr/bin/Rscript --vanilla --slave a <- c("Hello", "world", "!") print(a) b <- paste(a, collapse = " ") print(b)
Executing the script by
SHELL> chmod u+x an_rscript.r SHELL> ./an_rscript.r
Batch From Command
Note that the first line
#!/usr/bin/Rscript --vanilla --slave
is not necessary forRscript
. Of course, one can still useSHELL> Rscript an_rscript.r
or
SHELL> Rscript -e 'source("an_rscript.r")'
in command mode, too.
Example 2:
Hello world, Cottontail !
Make a file called "a_cottontail.r" containing the following.
# File name: a_cottontail.r a <- c("Hello", "world,", argv, "!") print(a) b <- paste(a, collapse = " ") print(b)
Executing the script by
SHELL> Rscript -e 'argv <- "Cottontail"; source("a_cottontail.r")'
More Cottontails !
There is the other way to take in arguments from STDIN by using
commandArgs()
in R. Let's make a file named "cottontails.r" as the following.# File name: cottontails.r eval(parse(text = rev(commandArgs())[1])) a <- c("Hello", "world,", argv, "!") print(a) b <- paste(a, collapse = " ") print(b)
Executing the script by
SHELL> Rscript cottontails.r 'argv <- "Cottontails"'