[R] scoping rules

Duncan Murdoch murdoch at stats.uwo.ca
Thu Sep 9 19:57:55 CEST 2004

On Thu, 9 Sep 2004 12:01:56 -0400 , Whit Armstrong
<Whit.Armstrong at tudor.com> wrote :

>Can someone help me with this simple example?
>sq <- function() {
>	y <- x^2
>	y
>myfunc <- function() {
>	x <- 10
>	sq()
>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" ?

The easiest (and best) is to pass x as an argument to sq.

Duncan Murdoch

More information about the R-help mailing list