I just uploaded the getopt package to CRAN. This will make it easy to use command line options with Rscript #! “shebang” scripts. It’s pretty much like what is available in every other programming language (getopt.h in C, Getopt::Long in Perl), but oddly was not yet available for R. So I wrote it!
Example usage, to print a sampling of a random normal variable, you might make a script named ./rnorm that contains:
#!/usr/bin/Rscript library('getopt'); opt = getopt(c( 'verbose', 'v', 2, "integer", 'help' , 'h', 0, "logical", 'count' , 'c', 1, "integer", 'mean' , 'm', 1, "double", 'sd' , 's', 1, "double" )); if ( !is.null(opt$help) ) { self = commandArgs()[1]; cat(paste("Usage: ",self," [-[gh]] [-[-mean|m] <mean>] [-[-sd|s] <sd>] [-[-count|c] <count>]\n",sep="")); q(status=1); } if ( is.null(opt$mean ) ) { opt$mean = 0 } if ( is.null(opt$sd ) ) { opt$sd = 1 } if ( is.null(opt$count ) ) { opt$count = 10 } if ( is.null(opt$verbose ) ) { opt$verbose = FALSE } if ( opt$verbose ) { write("writing...",stderr()); } cat(paste(rnorm(opt$count,mean=opt$mean,sd=opt$sd),collapse="\n")); cat("\n"); q(status=0);
and can be called, e.g., like:
blink:/tmp allenday$ ./rnorm -s 10 -c 10 --mean=100 --verbose=2 writing... 80.2953014070924 109.36715703278 104.856588724070 97.7983406914681 102.163515767212 90.7613417541473 97.8344921793064 108.918662445162 100.725143995218 105.285435884127 blink:/tmp allenday$
Yay! It’s a trivial example, but this can get pretty powerful once you can start passing in data files, reading from pipes, etc. I have some more example code for doing that, but it’s not getopt related so I need to dig it up.
Ok, I seriously need to get a syntax highlighter installed on this blog. Anyone have a recommendation? Isn’t there an enscript plugin for wordpress?
Update: I installed wp-syntax. There is no R support, but the C highlighter seems to work okay… wonder what it will do if I start doing the funky <- left arrow assign syntax…
Post a Comment