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

Paul Johnson pauljohn at ku.edu
Fri Mar 19 07:24:55 CET 2004


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.

-- 
Paul E. Johnson                       email: pauljohn at ku.edu
Dept. of Political Science            http://lark.cc.ku.edu/~pauljohn
1541 Lilac Lane, Rm 504                              
University of Kansas                  Office: (785) 864-9086
Lawrence, Kansas 66044-3177           FAX: (785) 864-5700




More information about the R-help mailing list