[R] Help on running regression by grouping firms

Hadley Wickham hadley at rice.edu
Thu Nov 25 23:39:21 CET 2010


> res <- function(x) resid(x)
> ds_test$u <- do.call(c, llply(mods, res))

I'd be a little careful with this, because there's no guarantee the
results will by ordered in the same way as the input (and I'd also
prefer ds_test$u <- unlist(llply(mods, res)) or ds_test$u <-
laply(mods, res))

> In your case, where you have multiple grouping factors, you may have to be a
> little more careful, but the strategy is the same. You could possibly reduce
> it to a one-liner (untested):
>
> ds_test$u <- do.call(c, dlply(ds_test, .(individual), function(x)
> resid(lm(size ~ time, data = x))))

Or:

ds_test <- ddply(ds_test, .(individual), transform, u = resid(lm(size ~ time)))

which will guarantee the correct ordering.

Hadley

-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



More information about the R-help mailing list