How to Run an R Script From the Command Line

Gustavo du Mortier Feb 02, 2024
R
  1. Rscript Options
  2. Execute Simple Expressions With the -e Parameter in Rscript
How to Run an R Script From the Command Line

The most convenient way to run R scripts from the command line is to use Rscript, an alternative front-end to run R code. Rscript is capable of executing R code from different command interpreters, such as a bash script on Linux or a Task Scheduler task on Windows.

To use Rscript, you have to execute the Rscript command from a command line accompanied by the script’s name to run, which is usually a .r file. To do this, you must know the path of both the Rscript executable and the R script. On Windows, the path to the Rscript executable usually is:

C:\Program Files\R\R-3.4.3\bin\Rscript.exe

To try Rscript, you can write the following script and save it with the name SayHi.r in the C:\scripts folder:

SayHi <- function(name) {
  sprintf("Hi, %s", name);
}

SayHi("Dave")

Then you can run it from the command line by navigating to the folder where the Rscript.exe file is installed and executing the following command:

Rscript.exe c:\scripts\SayHi.r

Output:

[1] "Hi, Dave"

Rscript Options

All Rscript options begin with --. You can use Rscript with the --help option to get detailed instructions on how to use the command, while the --version parameter shows the version of Rscript. If you want to get feedback on what Rscript does when running your script, you can use the --verbose option.

The --default-packages=list option (where list is a comma-separated list of package names) determines the packages loaded at startup by setting the environment variable R_DEFAULT_PACKAGES. If the --default-packages=list option is not used, Rscript checks an environment variable called R_SCRIPT_DEFAULT_PACKAGES. The contents of this variable take precedence over R_DEFAULT_PACKAGES.

Execute Simple Expressions With the -e Parameter in Rscript

Instead of specifying a script file to run, if you want to execute simple expressions in R, you can do it by specifying them in the same command line with the Rscript command, by using the -e parameter. For example, if you want to list the 4 first rows of the Iris dataset without creating a script file, you can execute the following from the command line:

Rscript -e "head(iris,4)"

Output:

 Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa

For more info on the Rscript command, check the official Rscript documentation.