[R] scoping problem?

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Jul 18 01:01:52 CEST 2001

Jonathan Qiang Li <jonqli at labs.agilent.com> writes:

> Hi, 
> I wrote a dummy function that passes a dataset to tree() as the
> following:
> test.func <- function(training.data){
> 	tr <- tree(type~., data = training.data)
> 	tr
> }
> Then I run the function under R
> > test.func(MyData)
> Error in model.frame.default(formula = type ~ ., data = training.data) : 
> 	Object "training.data" not found
> MyData resides in the working environment, while training.data does not.
> R manual
> claims that scoping of free variables are "lexical" (Introduction to R,
> chapter 10.7).
>  I take that it means that in evaluating the expression 
> tree(type~., data=training.data) ,
> R will look in the scope of the function test.func, therefore
> discovering "training.data" 
> as a "formal parameter". But it seemed that I misunderstood something
> here. 
> I also made a global variable 
> > training.data <- MyData
> and run 
> > test.func(MyData) 
> The function works fine without complaints.
> Can someone please help with this matter?

In general, you need to know that scoping and evaluation rules can be
broken in the R system. It is possible for a function to get a hold of
the expression that is passed for an argument and evaluate it in an
environment of its own choice, or even use the symbolic expression as
such (that is how you get away with saying "library(tree)" without
getting a "there is no object called `tree'" type error.)

tree() is doing some such trickery at the start of the function.
Basically, it gets hold of the entire call, and then replaces the
function being called with model.frame.default and reevaluates in the
parent frame. Or rather, it tries to do that. The code is using
eval(model, sys.parent()) and somehow that fails. 

Replacing sys.parent() with parent.frame() inside tree does make it
work, which points to a possible bug in eval() when used with an
integer envir= argument. Will have a look.

   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list