[Rd] prevent reassignment of function names
Henrik Bengtsson
hb at maths.lth.se
Fri Apr 7 00:49:02 CEST 2006
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
>
>
More information about the R-devel
mailing list