[R] Namespaces without packages?

R. Michael Weylandt michael.weylandt at gmail.com
Thu Sep 13 23:47:08 CEST 2012


On Thu, Sep 13, 2012 at 6:44 PM, Ray Griner <rgriner at sdac.harvard.edu> wrote:
> Dear R-help list -
>
> Here's my problem.  I have some programs I want to share with other users in the department.  I currently tell users to use source("/path/to/myfile.R") to include the program.  If I understand correctly, this puts all the functions I wrote into the user's namespace.

Global environment to be precise, but same idea.

>  So if I have a function my.func() and if the user already had a function named my.func(), I just replaced the user's function with my own.
>
> I know packages have a namespace mechanism.  Is there a way to put my functions into their own name space without using packages?   If yes, please let me know how.

It's a "yes, but..." sort of answer.

Put all the functions in their own environment, then attach that
environment to the search path:

E.g.,

f <- function(x) x + 2

g <- function(x) x + 5

en <- new.env()

en$f <- f
en$g <- g

attach(en)

rm(f)
rm(g)
rm(en)

f(6)
g(1:5)

but it's not necessarily a good idea... and you still have the
conflict problem you would have with packages.

> If no, that's OK, maybe we will decide that all shared files have to be in packages.  One reason we're avoiding packages is we might have a number of unrelated R functions and the question becomes whether each file should get put in it's own package or they all get put into a "miscellaneous" package.
>
> As a follow-up question, a local expert suggested packages are the way to go (but also suggested getting a 2nd opinion on R-help).

Yep, they really are... in fact the trickery above is a much
simplified version of what they do.

> If packages are the way to go, which is better:
> (a) we let users attach packages to the search path using library() and instruct them that they are responsible for avoiding any conflicts between names exported by the package and objects in their workspace?
> (b) we tell users not to use library() so that if they call package functions there are fully qualified names and no potential for conflict, i.e  PKG::myfunc()?

You could do both? Let them use library() but tell them to qualify if
there's a chance of danger. Alternatively, set a hook to periodically
run conflicts() and flip out if one is found. ;-)

Cheers,

Michael

>
> Thanks in advance -
>
> Ray Griner
> Statistical Programmer
> Center for Biostatistics in AIDS Research Harvard School of Public Health, Boston, MA
>
> ______________________________________________
> R-help at 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.




More information about the R-help mailing list