``commandArgs`` is the function in base R that lets you access arguments passed to Rscript, does not allow any fancy parsing of options but if you are not able to install optparse it is better than nothing.
- Trevor On Wed, Sep 12, 2012 at 1:32 PM, Tom Roche <tom_ro...@pobox.com> wrote: > > 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_ro...@pobox.com> > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.