tags:

views:

116

answers:

4

Is it possible in R to protect function names (or variables in general) so that they cannot be overwritten.

I recently spotted that this can be a problem when creating a data frame with the name "new", which masked a function used by lmer and thus stopped it working. (Recovery is easy once you know what the problem is, here "rm(new)" did it.)

+3  A: 

Maybe use environments! This is a great way to separate namespaces. For example:

> a <- new.env()
> assign('printer', function(x) print(x), envir=a)
> get('printer', envir=a)('test!')
[1] "test!"
Vince
Of course, someone could overwrite 'a' :)
geoffjentry
+1  A: 

@hdallazuanna recommends (via Twitter)

new <- 1
lockBinding('new', globalenv())

this makes sense when the variable is user created but does not, of course, prevent overwriting a function from a package.

JD Long
+3  A: 

There is an easy workaround for your problem, without worrying about protecting variable names (though playing with lockBinding does look fun). If a function becomes masked, as in your example, it is still possible to call the masked version, with the help of the :: operator.

In general, the syntax is packagename::variablename.

(If the function you want has not been exported from the package, then you need three colons instead, :::. This shouldn't apply in this case however.)

Richie Cotton
Doesn't work if I'm calling a function, in a package, which relies on a function elsewhere which inadvertently has become masked.
AndyF
@AndyF yeah that's a good point. I'm seeing a theme in the answers: R does not protect users from themselves. This is very Linux-like. ;)
JD Long