Running R from the Command Line

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"] <- "http://cran.r-project.org"
options(repos=r)
})
if (!require("pacman"))
{
install.packages("pacman")
library(pacman)
}
p_load(stats,dplyr,ggplot2,lubridate,install=TRUE)
The shell script file to run the R code looks like the following:
#!/bin/sh
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.