[R] R equivalent of python module structure and functionality?

J Toll jctoll at gmail.com
Wed Sep 12 01:47:52 CEST 2012


On Tue, Sep 11, 2012 at 6:00 PM, Tom Roche <Tom_Roche at pobox.com> wrote:
>
> 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)
>> foo(bar='baz')
>
> ? I'm looking for the 'R equivalent' of how python supports this
> usecase.
>
> details:
>
> As discussed in the thread beginning
>
> https://stat.ethz.ch/pipermail/r-help/2012-September/323255.html
>
> I have a script
>
> https://github.com/TomRoche/GEIA_to_netCDF/blob/master/netCDF.stats.to.stdout.r
>
> that takes named arguments without undue pain. I would also like to be
> able to call it as a function from other scripts. How to do that in R?
> In case that's not specific enough :-) I know how to structure files/
> modules in python like
>
> http://python.net/~goodger/projects/pycon/2007/idiomatic/cmdline.py
>
> (i.e., generically,
>
> http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#module-structure
>> """module docstring"""
>>
>> # imports
>> # constants
>> # exception classes
>> # interface functions
>> # classes
>> # internal functions & classes
>>
>> def main(...):
>>     ...
>>
>> if __name__ == '__main__':
>>     status = main()
>>     sys.exit(status)
>
> ) so that the file/module is both
>
> 1. callable from the OS commandline via, e.g.,
>
> $ /path/to/cmdline.py
>
> 2. importable without mere import causing execution of the script's
>    functionality, e.g.,
>
>>>> sys.path.append('/path/to')
>>>> from cmdline import *
>>>> process_command_line(...)
>
> How to do this in R?


Maybe take a look at littler.

"littler provides hash-bang (i.e. script starting with #!/some/path)
capability for GNU R, as well as simple command-line and piping use."

http://dirk.eddelbuettel.com/code/littler.html


James




More information about the R-help mailing list