Running R from the Command Line

Shoes for running
Photo by Nicholas Kinar


When working with the R programming language, one of the best (if not the best) IDE is R Studio.   But often I want to run scripts from the command line, allowing for all of the code to be easily reproducible.  Each R script does not have to be loaded into the IDE and manually re-run.

This is the procedure that I follow.

At the very top of each R file that will be run by an external shell script, I place the following code.  This code sets the default repository to download packages, and then installs (if required) the pacman utility to install other packages.  If the repository is not set, the script may not run outside of the R Studio environment.

The p_load function lists the different libraries to install and these will depend on your project.

 local({r <- getOption("repos")
       r["CRAN"] <- ""
if (!require("pacman"))

The shell script file to run the R code looks like the following:

export R_CALL="rscript"     # this is the executable to call
export R_LIBS=../install    # R package installation directory
$R_CALL file1.R &&           # list the R files here to run
$R_CALL file2.R              # add each successive filename

The R_CALL variable is the R executable to call, and this executable should be added to your PATH.   The R_LIBS is the installation directory for the R libraries.  You must have read and write access to this directory.

Running the shell script will progressively download the R libraries and run your code. The code is set up so that libraries will not be re-downloaded each time that a script file is run.



This article was updated on February 10, 2022

Dr. Nicholas J. Kinar

Dr. Nicholas J. Kinar is a hydrologist and researcher at the University of Saskatchewan. This is a blog of ideas, techniques and things that Nicholas perceives as unsophisticated knowledge in the Homeland of the Métis / Treaty 6 Territory / Saskatoon, Saskatchewan, Canada / Earth. His full name is Nicholas John Stanislaus Kinar. This blog of unsophisticated knowledge is intended to document some information that Nicholas finds useful. However, he does not mind if other people might find this information to be useful as well.

Related posts

VNC Connect

Accessing Mac OS X Desktop from a Windows Machine