Table of Contents

Rscript

Rscript allows you to directly invoke R scripts from a terminal command line, without having to use the cumbersome R CMD BATCH … syntax. This makes it very easy to parallelize statistical analyses across a cluster equipped with SGE or a similar job scheduler.

Hello World

Just like other shell scripts, you add a line like this to the top:

#! /usr/bin/Rscript

but modify it to point to wherever your Rscript executable actually got installed. It should be in the same directory as the main R executable.

Then we can write a simple Rscript like this:

hello.R
#! /usr/bin/Rscript
 
cat('Hello World.\n')

After we add permissions with chmod +x hello.R, we can execute our little program straight from the terminal command line like:

$ ./hello.R
Hello World.

Input arguments

By adding in this little bit of code at the top of your scripts, you can also flexibly take in different input arguments.

# Parse command line arguments    
args=(commandArgs(TRUE))   
for(i in 1:length(args)){
	eval(parse(text=args[i]))
}

Let's modify our “Hello World” script to print any string we give it.

printStr.R
#! /usr/bin/Rscript
 
# Input arguments:
# string - The string you want to print
 
# Parse command line arguments    
args=(commandArgs(TRUE))   
for(i in 1:length(args)){
	eval(parse(text=args[i]))
}
 
cat(c(string, '\n'))

When you call your script, the input arguments are R expressions that will get evaluated with the bit of code we added to parse them.

$ ./printStr.R "string='Another string'"
Another string
statistics/rscript.txt · Last modified: 2011/03/23 3:08 pm PDT by John Colby
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 4.0 International
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki