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

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Mar 19 10:38:09 CET 2004


On 19 Mar 2004, Peter Dalgaard wrote:

> Paul Johnson <pauljohn at ku.edu> writes:
> 
> > I've been reading the R mail archives and I've found  a lot of
> > messages with this same kind of problem, but I can't understand the
> > answers.  Can one of you try to explain this to me?
> > 
> > Here's my example. Given a regression model and a variable, I want to
> > use unstack() on the vector of residuals and make some magic with the
> > result. But unstack hates me.
> >  PCSE <- function (tmodel,groupVar) {
> >   myres1 <- resid(tmodel)
> >   resUnstacked <- unstack(myres1, form = myres1 ~ groupVar));
> >   E <- as.matrix(resUnstacked)
> >   SIGMA <- (1/nrow(E))*(t(E) %*% E)
> >   OMEGA <- diag(x=1, nrow=nrow(E), ncol=nrow(E)) %x% SIGMA
> > 
> >   X <- model.matrix(tmodel)
> >   XPRIMEXINV <- solve(t(X) %*% X)
> >   PCSECOVB <- XPRIMEXINV %*%  (t(X) %*% OMEGA %*% X ) %*% XPRIMEXINV
> > }
> > 
> > 
> > The error is:
> > PCSE(eld.ols1,dat2$STATEID)
> > Error in eval(expr, envir, enclos) : Object "groupVar" not found
> > 
> > Here's what I don't understand the most.
> >  If I hack this so that the "resUnstacked" is created by a "matrix"
> > command, then the function works. Why would matrix() work when unstack
> > does not.  And why does model.matrix() work if unstack does not.
> > 
> > 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.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list