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

Tom Roche Tom_Roche at pobox.com
Wed Sep 12 01:00:05 CEST 2012


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?

TIA, Tom Roche <Tom_Roche at pobox.com>



More information about the R-help mailing list