[R] lexical scope
Ramon Diaz
rdiaz at cnio.es
Tue Apr 22 12:22:39 CEST 2003
Dear Robin,
In terms of documentation I have found John Fox's "Frames, environments, and
scope in R and S-PLUS" (available at
http://socserv.socsci.mcmaster.ca/jfox/Books/companion/appendix-scope.pdf) to
be an excellent document.
"Lexical scope and statistical computing" by Gentleman & Ihaka (at the J.
Comp. Graph. Stat., 2000, 9: 491-508, though I think a pdf of a preprint can
be found somewhere in the net) contains more general discussion and more
ellaborate examples.
Finally, section 10.7 of "An introduction to R" has brief discussion of these
issues, but that should answer the specific questions you asked.
With regards to your specific situation:
x is a "free variable" for f, and f will look for it in (at? I'll never get
this right) the environment where it was defined (the global environment in
your example).
When you call f from g, f still looks for x in the environment where it was
defined; first time (before you rm(x)) x is 19 there; the second time, there
is no x anymore.
This behavior is different from that of S-PLUS.
Hope this helps,
Ramón
On Tuesday 22 April 2003 06:07, Robin Hankin wrote:
> Hi everyone
>
> another documented feature that was a bit unexpected for me:
>
> R> x <- 19
> R> f <- function(t){t+x}
> R> f(100)
> [1] 119
>
> --as expected: x is visible from within f()
> ..but...
>
>
> R> g <- function(a){x <- 1e99 ; return(f(a))}
> R> g(4)
> [1] 23
>
> --the "x" that is visible from within g() is just 19, which is not the
> one I expected it to find.
>
>
> R> rm(x)
> R> g(4)
> Error in f(a) : Object "x" not found
>
> --g() looks in the first search path place and finds it empty,
> returning an error.
>
>
> QUESTIONS:
> Why doesn't g() "keep looking" ?
> How do I tell g() where to find x?
> Where to look for documentation for this?
--
Ramón Díaz-Uriarte
Bioinformatics Unit
Centro Nacional de Investigaciones Oncológicas (CNIO)
(Spanish National Cancer Center)
Melchor Fernández Almagro, 3
28029 Madrid (Spain)
Fax: +-34-91-224-6972
Phone: +-34-91-224-6900
http://bioinfo.cnio.es/~rdiaz
More information about the R-help
mailing list