Running R from the command line

Much of the development and analysis work for my doctorate I do in R, which is an open-source statistics program based on the S-Plus language. Because I use R so often, there’s become a need to run the data from the command line to generate results.

One of my lingering questions has been how to script R from the command line and give it custom arguments. Here’s how you do it:

#!/usr/bin/Rscript --vanilla

args <- commandArgs(TRUE)
if (length(args) != 1) {
 print ("Usage: Rscript <script> <directory>")

cwd <- args[1]

Basically, the program that you run from the command line is Rscript. It came installed by default on my computer when I installed the R packages.

The first line is the shebang: #!/usr/bin/Rscript. You can specify extra command-line parameters to the Rscript command here. In this case, we use –vanilla, which means to initialize a clean environment. You can use other ones like –save, which saves the workspace at the end of the session, and –restore, which reads the previous session and restores it.

The next line is important: the commandArgs() function reads the command line arguments and stores them in a vector of strings so that you can process them. You can see that I check for arguments as well.

Finally you can address each argument using args as an array.

If you need to parse out the arguments you can try using match.arg to match individual parameters!

Type ?Rscript in the R environment to get the manual page for details.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s