[Rd] prevent reassignment of function names

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Apr 7 09:39:03 CEST 2006


On Fri, 7 Apr 2006, Henrik Bengtsson wrote:

> On 4/6/06, Seth Falcon <sfalcon at fhcrc.org> wrote:
>> Tim Bergsma <timb at metrumrg.com> writes:
>>
>>> Hi.
>>>
>>> I'm trying to find a systematic way to prevent assignment to names of
>>> existing functions.
>>
>> An alternative would be to put your functions into an R package with a
>> namespace.  Then you won't be able to overwrite them (easily).
>
> Can even be a package without a namespace - to overwrite anything in a
> package you have to explicitly do assign() to the environment of the
> package.

I don't think the concern was actually to 'overwrite' but rather to 
redefine, which you can do by masking.  To quote the original post

   'I'm trying to find a systematic way to prevent assignment to names of
    existing functions.'

Note, `to names'.  Namespaces obviate masking of names of functions in 
your package or in base, and from other namespaces you import.

>
> Another way is to add an environment to the search path (?search) and
> add you functions to that.  Example:
>
> # Add an empty environment to the search path
> env <- attach(list(), name="myFunctions")
>
> # Define functions
> assign("foo", function(x) { cat("foo: x=", x, "\n", sep="") }, envir=env)
> assign("bar", function(x) { cat("bar: x=", x, "\n", sep="") }, envir=env)
>
> # Assign 'foo' in the global environment
> foo <- 3
>
> # Function foo() is still available in 'myFunctions'
> foo(4)
>
> If you have a myFunction.R file with function definitions, e.g.
>
> foo <- function(x) {
>  cat("foo: x=", x, "\n", sep="")
> }
>
> bar <- function(x) {
>  cat("bar: x=", x, "\n", sep="")
> }
>
> then it's a bit tricky to make source() assign objects to the
> environment.  Instead you can use sourceTo() in the R.utils package,
> e.g.
>
> sourceTo("myFunctions.R", envir=env)
>
> /Henrik
>
>> + seth
>>
>> ______________________________________________
>> R-devel at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-devel
>>
>>
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list