Skip to content

Template for R scripts

mdijkstra edited this page Sep 22, 2014 · 12 revisions

R scripts

Please use the following example for parsing command line parameters. Please add a short description of the script's purpose after the #DOC-directive at the second line of the script.

#!/usr/bin/env Rscript
DOC = "This script illustrates how R can parse arguments if called from the command line."

# Load package
suppressPackageStartupMessages(library("argparse"))

# Create parser object
parser <- ArgumentParser(description = DOC)

parser$add_argument("-v", "--verbose", action="store_true", default=TRUE, help="Print extra output [default]")
parser$add_argument("-q", "--quietly", action="store_false", dest="verbose", help="Print little output")
parser$add_argument("-c", "--count", type="integer", default=5, help="Number of random normals to generate [default %(default)s]", metavar="number")
parser$add_argument("--generator", default="rnorm", help = "Function to generate random deviates [default \"%(default)s\"]")
parser$add_argument("--mean", default=0, type="double", help="Mean if generator == \"rnorm\" [default %(default)s]")
parser$add_argument("--sd", default=1, type="double", metavar="standard deviation", help="Standard deviation if generator == \"rnorm\" [default %(default)s]")
# Please note: you can add 'required = TRUE' for parameters that are required

args <- parser$parse_args()

# Print some progress messages to stderr if "quietly" wasn't requested

if ( args$verbose ) { write("Writing some verbose output to standard error...\n", stderr()) }

# Do some operations based on user input
if("rnorm" == args$generator) {
	cat(paste(rnorm(args$count, mean=args$mean, sd=args$sd), collapse="\n"))
} else {
	cat(paste(do.call(args$generator, list(args$count)), collapse="\n"))
}
cat("\n")

If you'd save this script as demo.R, make it executable (chmod +x demo.R), running

./demo.R -h

will give the following result.

usage: ./demo.R [-h] [-v] [-q] [-c number] [--generator GENERATOR]
                [--mean MEAN] [--sd standard deviation]

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         Print extra output [default]
  -q, --quietly         Print little output
  -c number, --count number
                        Number of random normals to generate [default 5]
  --generator GENERATOR
                        Function to generate random deviates [default "rnorm"]
  --mean MEAN           Mean if generator == "rnorm" [default 0]
  --sd standard deviation
                        Standard deviation if generator == "rnorm" [default 1]
Clone this wiki locally