[R-sig-Geo] R Scoping Rules
Thomas Lumley
tlumley at u.washington.edu
Mon Apr 19 18:06:48 CEST 2010
On Sun, 18 Apr 2010, Stephen G. Eick wrote:
> simple<-function() {
>
> if(exists("height"))
>
> cat("height exists\n")
>
> else
>
> cat("height does not exist\n")
>
> }
>
>
>
> foo<-function() {
>
> height<-10
>
> simple()
>
> }
>
>
>
>> foo()
>
> height does not exist
>
>
>
> Can somebody please explain why "simple" does not find the "height" variable
> when I run it?
>
'height' is neither a local variable, nor visible in the environment where 'simple()' was defined. That's the point of static lexical scope -- the scope depends on what was visible where the function was defined.
You seem to want dynamic scope, where variables in the calling environment are visible. This can be faked with eval.parent(), but isn't how R naturally works.
>
> Is there an easy way to make R use scoping rules like python where it
> searches over all frames to find the value of an symbol?
R *does* use scoping rules like python (since python 2.1). Your example doesn't work in python, for exactly the same reason.
>>> def simple():
... print height
...
>>> def foo():
... height = 10
... simple()
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in foo
File "<stdin>", line 2, in simple
NameError: global name 'height' is not defined
-thomas
Thomas Lumley Assoc. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
More information about the R-sig-Geo
mailing list