From hb at maths.lth.se  Fri Apr  7 00:49:02 2006
From: hb at maths.lth.se (Henrik Bengtsson)
Date: Fri, 7 Apr 2006 00:49:02 +0200
Subject: [Rd] prevent reassignment of function names
In-Reply-To: <m21wwa1in9.fsf@ziti.local>
References: <44357024.6090804@metrumrg.com> <m21wwa1in9.fsf@ziti.local>
Message-ID: <59d7961d0604061549k4ee706bn7384430c55b83858@mail.gmail.com>

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.

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



[Rd] prevent reassignment of function names
Henrik Bengtsson