[R] scoping rules

Thomas Lumley tlumley at u.washington.edu
Mon Sep 13 13:56:37 CEST 2004

On Thu, 9 Sep 2004, Whit Armstrong wrote:

> Can someone help me with this simple example?
> sq <- function() {
> 	y <- x^2
> 	y
> }
> myfunc <- function() {
> 	x <- 10
> 	sq()
> }
> myfunc()
> executing the above in R yields:
>> myfunc()
> Error in sq() : Object "x" not found
> I understand that R's scoping rules cause it to look for "x" in the
> environment in which "sq" was defined (the global environment in this case).
> But in this case "x" is defined inside the calling function, not the
> environment in which "sq" was defined.
> Is there a way to tell R to look in the calling function for "x" ?

yes, but you almost certainllyy don't want to.

In a real example you would want to either

1/ Pass x as an argument (most likely)
2/ Define sq() inside myfunc()
3/ define myfunc() inside sq()
4/ Pass the name of x as an argument (eg quote(x) or ~x)

While you can fake dynamic scope in R, there is no point in doing it with 
a variable whose name is hard-coded.

The only reason to allow access to a non-local variable x with a fixed 
name is to preserve its value across calls to the function, but with 
dynamic scope the "x" may be a completely different variable each time.


More information about the R-help mailing list