R equivalent of python module structure and functionality?
https://stat.ethz.ch/pipermail/r-help/2012-September/323551.html (slightly edited)
how to structure an R file such that it can be both
1. used as a script via, e.g., (from OS commandline)
$ Rscript foo.r bar=baz
2. imported and called as a function via, e.g. (from R commandline)
source('./foo.r')
or otherwise loaded, then called, e.g.
foo(bar='baz')
? I'm looking for the 'R equivalent' of how python supports this
Big thanks to Trevor Davis! https://stat.ethz.ch/pipermail/r-help/2012-September/323559.html
The optparse package is what you would want [to parse args for] a script i.e.``Rscript foo.R --bar=baz`` in a pythonic manner.
Unfortunately, the R on the cluster on which I'm working currently lacks that package, and I lack root on that cluster. But your example (below) works on my box (where I'm root).
The other piece of the puzzle is the ``interactive()`` function which lets you know if you are are calling from the "R commandline".
...
Example:
one syntax error fixed
### begin foo.R #####
# define foo function
foo <- function(bar) {
print(bar)
}
# if not interactive we are calling from OS command line
# parse args and call function foo
if(!interactive()) {
suppressPackageStartupMessages(library("optparse"))
option_list <- list(
make_option(c("-b", "--bar"), default="hello world")
)
opt <- parse_args(OptionParser(option_list=option_list))
foo(bar=opt$bar)
}
##### end foo.R ######
And I have modified my code @ https://github.com/TomRoche/GEIA_to_netCDF/commit/f982de0660b10f380183e34a0f1557a4cb1c5bb7 accordingly (to use `interactive()`, anyway). Thanks again! Tom Roche <Tom_Roche at pobox.com>