>> I also wanted to point Tom to CRAN packages
>>     getopt
>>     optparse
>> written specifically to support command-line argument parsing with R
>
>Thanks, but again, I'm not seeing how those solve the given problem(s).
>Am I missing something?

The optparse package, tested with Rscript but probably works with littler,
provides an API similar but less powerful that what was a major python
module for the parsing of optional arguments before the optparse module was
deprecated in favor of the argparse module.  So quite relevant for half the
problem, no?  It is what you would want if you wanted to use a script
i.e.``Rscript foo.R --bar=baz`` in a pythonic manner.

> summary: 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')

The other piece of the puzzle is the ``interactive()`` function which lets
you know if you are are calling from the "R commandline".  So define your
function foo in your script and at the end if you aren't in an interactive
session parse some arguments and call your function with those arguments,
otherwise if you simply source it then you should have access to that
function to call as you please.  Example:

### 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  ######

So

bash#   Rscript foo.R --bar="baz"

or

> source("foo.R")
> foo(bar="baz")

Should both work.

- Trevor

        [[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.

Reply via email to