Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# st: RE: simplifying foreach loop

 From Nick Cox <[email protected]> To "'[email protected]'" <[email protected]> Subject st: RE: simplifying foreach loop Date Mon, 11 Oct 2010 20:40:57 +0100

```Your approach is not going to work for a reason explained to you by Maarten Buis earlier today.

Consider

by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2010 &
sic_n<=2019
by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2020 &
sic_n<=2029

Once the first command is completed, the second will fail because the variable -datmedian- already exists, and -egen- needs a new variable to work.

But you just need a coarsened SIC variable.

gen sic_n_2 = 10 * floor(sic_n/10)
egen datmedian = median(r_d), by(sic_n_2)

No loops at all!

Nick
[email protected]

Biljana Dlab

I have firms sorted by SIC from 2000-3999 and would like to compute the
3-digit industry median.

How do I simplify this loop, so that the increment in sic_n are
increasing by 10 without writing out every line?

. foreach v of var r_d {
2. gen d`v'=.
3. by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2010 &
sic_n<=2019
4. by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2020 &
sic_n<=2029
5. by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2030 &
sic_n<=2039
6. by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2040 &
sic_n<=2049
7. by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2050 &
sic_n<=2059
8. by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2060 &
sic_n<=2069
9. by sic_n, sort: egen datmedian=median(r_d) if sic_n>=2070 &
sic_n<=2079
(...)
till
by sic_n, sort: egen datmedian=median(r_d) if sic_n>3990 &
sic_n<3999
}

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```