Java Mailing List Archive

http://www.r-help.com/

Home » R Help for Statistical Computing »

Re: [R] Warning when trying to access a variable out of scope?

Duncan Murdoch

2009-07-03

Replies: Find Java Web Hosting

Author LoginPost Reply
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

______________________________________________
R-help@(protected)
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
©2008 r-help.com - Jax Systems, LLC, U.S.A.