A script is a, collection of statements/functions, that can be run independently from the command line interface i.e. a terminal.

A simple example is provided below and it can be a copied into a new file test.R.

# code for test.R
for (i in seq(1:10)){
  print(i)
}

To execute it from the terminal, we call Rscript which will interpret and execute the R code in test.R:

Rscript test.R

Command line arguments

You can also supply input options to the R scripts, using the function commandArgs. To run the tiny script provided below, copy it into a file of your choice myfavourite.R and run it using the command Rscript myfavourite.R 19 28.

# test script 2 with command line options
args <- commandArgs(trailingOnly = TRUE)
a <- as.integer(args[1]) # guess why I had to use coercion
b <- as.integer(args[2])
print(a)
print(b)
print(a+b)

A little more complex script t1_plot_dist.R has been provided in the examples folder of CS5701 module. You are welcome to test it out to produce the image below:

Figure caption: A time series plot

 

Introduction to R by Dr. Sarath Chandra Dantu

This course material is available under a Creative Commons BY-SA license (CC BY-SA) version 4.0