Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: Re: foreach program


From   "Michael Blasnik" <[email protected]>
To   <[email protected]>
Subject   st: Re: foreach program
Date   Fri, 08 Sep 2006 12:02:24 -0400

I've been reading this thread and don't understand why you need to loop at all or generate the grouping variable. Wouldn't it make more sense to use a collapse and a reshape?

keep if inrange(age,15,19)
gen byte groupqtrs=(gqtyped==200)
collapse (sum) perwt, by(fip race sex groupqtrs)
reshape wide perwt, i(fip race sex) j(groupqtrs)
gen totpersons=perwt0+perwt1
gen ir=perwt1/totpersons

This approach seems easier and faster and gives you a dataset of results directly.
You could take the results and merge them back into the main dataset if you want, but I don't even think that is necessary.

Michael Blasnik
[email protected]

----- Original Message ----- From: "Scott Cunningham" <[email protected]>
To: <[email protected]>
Sent: Friday, September 08, 2006 10:47 AM
Subject: st: foreach program
<snip>


egen group=group(fip race sex)
su group, meanonly

foreach i of num 1/`r(max)' {
gen i=perwt if age>=15 & age<=19 & group==`i' & gqtyped==200
gen p=perwt if age>=15 & age<=19 & group==`i'
egen itot=sum(i)
egen ptot=sum(p)
replace ir_level=itot if age==15 & group==`i'
replace pop_level=ptot if age==15 & group==`i' replace ir=itot/ptot if age==15 & group==`i'
drop i p itot ptot
}
*
*   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/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index