optparse R package for creating command line scripts with arguments

R
Linux
Author

Vinh Nguyen

Published

July 25, 2014

Just discovered the optparse package in R that allows me to write a command line R script that could incorporate arguments (similar to Python's argparse). Here's an example:

```{r}
#! /usr/bin/env Rscript

# http://cran.r-project.org/web/packages/optparse/vignettes/optparse.pdf
suppressPackageStartupMessages(library("optparse"))

option_list <- list(
    make_option(c('-d', '--date'), action='store', dest='date', type='character', default=Sys.Date(), metavar='"YYYY-MM-DD"', help='As of date to extract data from.  Defaults to today.')
)

opt <- parse_args(OptionParser(option_list=option_list))

# print(opt$date)
cat(sprintf('select * where contract_date > "%s"\n', opt$date) 
```

Save this as my_scrypt.R, and do chmod +x my_script.R. Now check out ./my_script.R --help.