[R] Warning when trying to access a variable out of scope?
Duncan Murdoch
murdoch at stats.uwo.ca
Sat Jul 4 01:59:04 CEST 2009
On 03/07/2009 3:28 PM, Greg Snow wrote:
> Does this do what you want?
>
>> b.test <- 3
>>
>> f <- function(a,b) {
> + a+b.test
> + }
>> f(10,20)
> [1] 13
>> environment(f) <- baseenv()
>>
>> f(10,20)
> Error in f(10, 20) : object 'b.test' not found
Probably not: it messes up cases where f needs to call functions in the
global environment, or in stats, or some other package. It might be
better to say
environment(f) <- parent.env(globalenv())
but that has problems too.
The question really isn't solvable in R. Since functions and variables
aren't very different, and since any non-trivial function needs to make
use of functions outside itself, just about every function makes use of
globals. Usually that's fine, they're globals like "mean". Sometimes
it's not fine, they're globals like "b.test", which aren't meant to be
seen.
codetools does a pretty good job of detecting these sorts of errors, but
there really isn't a foolproof test.
Duncan Murdoch
More information about the R-help
mailing list