[R] using "unstack" inside my function: that old scope problem again

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Mar 19 11:20:13 CET 2004


Prof Brian Ripley <ripley at stats.ox.ac.uk> writes:

> > > Thanks in advance, as usual.
> > 
> > Look inside getAnywhere(unstack.default) and you'll find things like
> > 
> > x <- as.list(x)
> > ...
> > res <- c(tapply(eval(form[[2]], x), eval(form[[3]], x), as.vector))
> > 
> > 
> > Now, "x" is myres1, form[[2]] is quote(myres1), and form[[3]] is
> > quote(groupVar). myres1 would appear to be a vector and I suspect it
> > doesn't have any elements of that name...
> 
> But it is not documented that `form' refers only to columns of x.
> Is that the intention?  I thought not.

Unstack() is defined as the reverse of stack(), so it is not really
well defined what to expect of the default method. However, I think
you're right that something is wrong: If you run unstack at the
command level you'd pick up items in the global environment, but the
similar thing doesn't happen inside a function. You'd likely want the
eval()s to use enclos=parent.frame(), or maybe the whole thing wants
to be eval(...,environment(form)).

I'm also puzzled about the as.list thing. It doesn't seem to do what I
would expect such a thing to do...

> x <- rnorm(6)
> g <- gl(2,3)
> unstack(x,x~g)
NULL data frame with 0 rows
> unstack(list(x),x~g)
Error in tapply(eval(form[[2]], x), eval(form[[3]], x), as.vector) :
        arguments must have same length
> unstack(list(x=x),x~g)
          X1          X2
1 -1.1093047 -0.02241302
2  0.6129984  0.22170428
3  1.1512541  0.17254144


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




More information about the R-help mailing list