Running R scripts from command line

Two options are available to run .R files from command line:

  • Rscript


It can be read that the R CMD BATH must be used as [1]:

R CMD BATCH [options] infile [outfile]

So lets see an example, creating an source.R file with the following content:

rnorm(n=5, mean=2)

Then run the script using the R CMD BATHC. The results of the executions is stored into a file called source.Rout:

[carleshf@lambdafunction tmp]$ R CMD BATCH source.R 
[carleshf@lambdafunction tmp]$ ll
total 8
-rw-rw-r--. 1 carleshf carleshf   42 feb  5 09:35 source.R
-rw-rw-r--. 1 carleshf carleshf 1020 feb  5 09:35 source.Rout

The content of the source.Rout is the result of the operation(s) we saved into the R script file (source.R):

[carleshf@lambdafunction tmp]$ cat source.Rout 

R version 3.0.2 (2013-09-25) -- "Frisbee Sailing"
Copyright (C) 2013 The R Foundation for Statistical Computing
Platform: x86_64-unknown-linux-gnu (64-bit)


R> rnorm(n=5, mean=2)
> proc.time()
   user  system elapsed 
  0.166   0.021   0.181

The problem with R CMD BATCH is there is no way to pass arguments to the R script file from the command line in itself.


It can be read that the Rscript must be used as [2]:

Rscript [options] [-e expression] file [args]

Using the same example as before, the source.R can be run as:

[carleshf@lambdafunction tmp]$ Rscript source.R

And no output is displayed nor stored. We can change our R script to save the calculated values:

res <- rnorm(n=5, mean=2)
write.table(res, file="source.Rout")

And the results, stored into source.Rout is:

[carleshf@lambdafunction tmp]$ cat source.Rout 
"1" 2.5619050922511
"2" 1.42802439164873
"3" 1.31925385276224
"4" 2.5502466455518
"5" 0.341230739600524

But with Rscript we can read the arguments from the command line using commandArgs(). So, using this commandArgs(), the source.R must be:

args <- commandArgs(trailingOnly = TRUE)
res <- rnorm(n=as.numeric(args[1]), mean=as.numeric(args[2]))
write.table(res, file="source.Rout")

And it must be run as:

[carleshf@lambdafunction tmp]$ Rscript source.R 1 2

So, the content, stored into source.Rout, is:

[carleshf@lambdafunction tmp]$ cat source.Rout 
"1" 1.68212091424515


  • [1] CMD BATCH documentation: link
  • [2] Rscript documentation: link

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: