2013年7月2日星期二

parsing arguements in a R script

http://ggorjan.blogspot.ca/2013/07/parse-arguments-of-r-script.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+GregorGorjancsBlog+(Gregor+Gorjanc's+blog)

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 arguments
args <- a="" href="http://inside-r.org/r-doc/base/commandArgs" style="color: #b81909; text-decoration: none;">commandArgs
(TRUE)   ## Default setting when no arguments passed if(length(args) < 1) { args <- a="" href="http://inside-r.org/r-doc/base/c" style="color: #b81909; text-decoration: none;">c("--help") }   ## Help section if("--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 <- a="" href="http://inside-r.org/r-doc/base/function" style="color: #b81909; text-decoration: none;">function(x) strsplit(sub("^--", "", x), "=") argsDF <- a="" href="http://inside-r.org/r-doc/base/as.data.frame" style="color: #b81909; text-decoration: none;">as.data.frame(do.call("rbind", parseArgs(args))) argsL <- a="" href="http://inside-r.org/r-doc/base/as.list" style="color: #b81909; text-decoration: none;">as.list(as.character(argsDF$V2)) names(argsL) <- argsdf="" nbsp="" span="" style="font-style: italic;">## Arg1 default if(is.null(args$arg1)) { ## do something }   ## Arg2 default if(is.null(args$arg2)) { ## do something }   ## Arg3 default if(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.

没有评论:

发表评论