[R] scoping rules

Whit Armstrong Whit.Armstrong at tudor.com
Thu Sep 9 18:01:56 CEST 2004

Can someone help me with this simple example?

sq <- function() {
	y <- x^2

myfunc <- function() {
	x <- 10


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" ?

I have tried the following variants of "eval" such as
eval(sq(),parent.frame()) with no success.

Thanks for your help.


> R.Version()
[1] "i386-pc-mingw32"

[1] "i386"

[1] "mingw32"

[1] "i386, mingw32"

[1] ""

[1] "1"

[1] "9.1"

[1] "2004"

[1] "06"

[1] "21"

[1] "R"


More information about the R-help mailing list