[R] Define "local" function

Duncan Murdoch murdoch at math.aau.dk
Sat Apr 16 11:16:50 CEST 2005


Peter Dalgaard wrote:
> Ales Ziberna <ales.ziberna at guest.arnes.si> writes:
> 
> 
>>I am also very interested how this could be done, possibly in such a
>>way that this would be incorporated in the function itself and there
>>wouldn't be a need to write "environment(f) <- NULL" before calling a
>>function, as is proposed in the reply below and in a thread a few days
>>ago!

Why worry about where the line occurs?  In R, there is little 
distinction between functions and data, so you could say that the 
function definition isn't done until you're finished modifying it.

> Notice BTW, that environment(f) <- NULL may have unexpected
> consequences. What it really means is that the lexical scope of f
> becomes the base package. This interpretation of NULL may change in
> the future, since it is somewhat illogical and it has a couple of
> undesirable consequences that there's no way to specify a truly empty
> environment. So
> 
> a) if you're calling a function outside of the base package, you get
> the effect of
> 
> 
>>f <- function(){mean(rnorm(10))}
>>environment(f)<-NULL
>>f()
> 
> Error in mean(rnorm(10)) : couldn't find function "rnorm"
> 
> b) even if it does work now, it may be broken by a future change to R.
> Notice that *all* functions contain unbound variables in the form of
> functions so if we get an empty NULL environment, even "<-" may stop
> working. 

A more likely thing to want to do is to see the search path only after 
the global environment, which you can do with

environment(f) <- as.environment(2)

(the 2 says to use the 2nd environment on the search path).  This might 
not be perfect, since you can use attach() to modify the search path, 
but it would likely be good enough to flush out simple programming bugs.

Duncan Murdoch




More information about the R-help mailing list