I concur with the advice to start
with -levels-, but this seems a little
more complicated than it need be.
levels company, local(C)
gen zresid = .
qui foreach c of local C {
regress y x1 x2 x3 if company == `c'
predict temp, rstudent
replace zresid = temp if company == `c'
drop temp
}
save data_with_zresid
Nick
[email protected]
Roger Newson replied to David Bernstein
> >How do I retain my predicted values from a regression
> >when using the "by group" command?
> >
> >for example:
> >
> >by company: reg x y1 y2 y3
> >predict zresid, rstudent
> >
> >Is it possible to create a data file that contains the
> >zresids that is associated with the regression for
> >each each company?
>
> I think the best way is probably in a loop, using the official Stata
> -levels- command and my own -dsconcat- package (downloadable
> from SSC),
> similarly to the following (assuming that -company- is an
> integer-valued
> variable):
>
> levels company
> local coms "`r(levels)'"
> preserve
> local flist ""
> local i1=0
> foreach com of numlist `coms' {
> local i1=`i1'+1
> tempfile tf`i1'
> restore, preserve
> keep if company==`com'
> regress x y1 y2 y3
> predict zresid, rstudent
> save `tf`i1'', replace
> local flist "`flist' `tf`i1''"
> }
> dsconcat `flist'
>
> This should cause the memory to contain a data set with the existing
> variables plus a new variable -zresid- containing studentised
> residuals. In
> the more general case, where by-groups may be based on
> multiple variables,
> you can use the official Stata -gsort- command with the -generate()-
> option. And, if you also want to save the model parameters,
> then you might
> use the -parmest- package, also downloadable from SSC.
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/