# Parse arguments of an R script

July 2, 2013
By

(This article was first published on Gregor Gorjanc (gg), and kindly contributed to R-bloggers)

R can be used also as a scripting tool. We just need to add shebang in the first line of a file (script):

#!/usr/bin/Rscript

and then the R code should follow.

Often we want to pass arguments to such a script, which can be collected in the script by the commandArgs() function. Then we need to parse the arguments and conditional on them do something. I came with a rather general way of parsing these arguments using simply these few lines:

## Collect argumentsargs <- commandArgs(TRUE) ## Default setting when no arguments passedif(length(args) < 1) {  args <- c("--help")} ## Help sectionif("--help" %in% args) {  cat("      The R Script       Arguments:      --arg1=someValue   - numeric, blah blah      --arg2=someValue   - character, blah blah      --arg3=someValue   - logical, blah blah      --help              - print this text       Example:      ./test.R --arg1=1 --arg2="output.txt" --arg3=TRUE \n\n")   q(save="no")} ## Parse arguments (we expect the form --arg=value)parseArgs <- function(x) strsplit(sub("^--", "", x), "=")argsDF <- as.data.frame(do.call("rbind", parseArgs(args)))argsL <- as.list(as.character(argsDF$V2))names(argsL) <- argsDF$V1 ## Arg1 defaultif(is.null(args$arg1)) { ## do something} ## Arg2 defaultif(is.null(args$arg2)) {  ## do something} ## Arg3 defaultif(is.null(args\$arg3)) {  ## do something}

## ... your code here ...
Created by Pretty R at inside-R.org

It is some work, but I find it pretty neat and use it for quite a while now. I do wonder what others have come up for this task. I hope I did not miss some very general solution.

To leave a comment for the author, please follow the link and comment on his blog: Gregor Gorjanc (gg).

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.