how to structure an R file such that it can be both
1. used as a script via, e.g., (from OS commandline)
2. imported and called as a function via, e.g. (from R commandline)
or otherwise loaded, then called, e.g.
? I'm looking for the 'R equivalent' of how python supports this
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".
# 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)
}