[R] scoping rules

Gabor Grothendieck ggrothendieck at myway.com
Thu Sep 9 18:28:17 CEST 2004


Whit Armstrong <Whit.Armstrong <at> tudor.com> writes:

: 
: 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.
: 



Here are two approaches:

1. have myfunc change sq's environment to the current environment:

sq <- function() { y <- x^2; y }
myfunc <- function() { x <- 10; environment(sq) <- environment(); sq() }
myfunc()

2. modify sq itself to get x from the parent frame.  We use get in
the example below but you could alternately replace get(...) with
eval.parent(substitute(x)) if you prefer to use eval:

sq <- function() { y <- get("x", parent.frame())^2; y }
myfunc <- function() { x <- 10; sq() }
myfunc()




More information about the R-help mailing list