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

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

Thanks for your help.

Regards,
Whit

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

$arch
[1] "i386"

$os
[1] "mingw32"

$system
[1] "i386, mingw32"

$status
[1] ""

$major
[1] "1"

$minor
[1] "9.1"

$year
[1] "2004"

$month
[1] "06"

$day
[1] "21"

$language
[1] "R"

>




More information about the R-help mailing list