[R] scoping problem?

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Jul 18 02:06:16 CEST 2001


Peter Dalgaard BSA <p.dalgaard at biostat.ku.dk> writes:

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

Hmm. Digging a little deeper got me to the following code in do_eval
(eval.c) 

    case INTSXP:
    case REALSXP:
        nback = asInteger(env);
        if (nback==NA_INTEGER)
            errorcall(call,"invalid environment");
        if (nback > 0 )
            nback -= framedepth(R_GlobalContext);
        nback = -nback;
        PROTECT(env = R_sysframe(nback,R_GlobalContext));
        break;

This indicates that the interpretation of an integer argument to eval
is the number of frames to go back if it is *positive*. This is the
opposite of what sys.call/sys.frame does, and besides, R_sysframe does
the positive/negative conversion itself. Apparently, this code has
been sitting there "forever"... 

I think it ought to be just

    case INTSXP:
    case REALSXP:
        nback = asInteger(env);
        if (nback==NA_INTEGER)
            errorcall(call,"invalid environment");
        PROTECT(env = R_sysframe(nback,R_GlobalContext));
        break;

(possibly with a change of variable name for "nback").

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