Run R scripts from the command line on Ubuntu

Running R scripts from the command line can be a powerful way to:

  • Automate your R scripts
  • Integrate R into production
  • Call R through other tools or systems
There are basically two Linux commands that are used:
  1. RScript (preferred)
  2. The older command is  R CMD BATCH.

A better way to run R scripts in batch mode is Rscript, and its comes with R.

See the example below to see the difference between using RScript and R CMD BATCH.

Save 

print("hello world")

as a r script file and name it helloworld.r, and then run it in your terminal:

(Be sure to first cd to the path where you saved the helloworld.r file.)

then type the commands (the lines below in bold) to your temrinal

$ Rscript helloworld.r
[1] "hello world"
$ R CMD BATCH helloworld.r
$

We can see that Rscript directly  output to the terminal , and R CMD BATCH has done nothing. But actually, R CMD BATCH has written its output to a file called helloworld.r.Rout(it is located at the same place where you put helloworld.r), and that output includes both the commands and output, just like in interactive mode, along with some runtime stats:

> print("hello world")
[1] "hello world"
> 
> 
> proc.time()
   user  system elapsed 
  0.080   0.004   0.113

You can call these directly from the command line or integrate them into a bash script. You can also call these from any job scheduler.

Note, these are R related tools. The RStudio IDE does not currently come with tools that enhance or manage the RScript and R CMD BATCH functions. However, there is a shell built into the IDE and you could conceivably call these commands from there.

 The alternative to the using the Linux command line is to use the source() function inside of R. The source function will also call a script, but you have to be inside an R session to use it.

References:

How to run R scripts from the command line (Nathan Stephens on January 02, 2017)

Running R batch mode on Linux (pdf)

RScript man page

Leave a Reply

Your email address will not be published. Required fields are marked *