How to run R scripts from the command line


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. The first is the command, Rscript, and is preferred. The older command is R CMD BATCH. 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.
Here are a few external references to the Rscript and R CMD BATCH commands: