# Re: st: loop 2+ not calculating

 From Keith Dear To statalist@hsphsun2.harvard.edu Subject Re: st: loop 2+ not calculating Date Tue, 19 Feb 2008 13:17:28 +1100

William,
Your code fails because temp[`t'-1] always points to the first company.
The following works, though there are probably better ways that avoid the nested loops

webuse grunfeld, clear
su time, meanonly
loc Max=r(max)
levelsof com, local(is)
g mdn=.
qui foreach i of local is {
forval t = 2/`Max' {
centile kst if com==`i'&time<`t'
replace mdn=r(c_1) if com==`i'&time==`t'
}
}

Keith

At 12:59 PM 19/02/2008, you wrote:

```I'm trying to create a median for the previous observations (not
including the current observation) by company .  The code below works
for the first loop (company 1) but after that it just has missing
values for the median.  I don't understand why.  Any ideas on what I'm
doing wrong.

webuse grunfeld, clear
su time, meanonly
loc Max=r(max)
levelsof com, local(is)
g mdn=.
foreach i of local is {
forval t = 2/`Max' {
egen temp=median(kst) if com==`i'&time<`t'
qui replace mdn=temp[`t'-1] if com==`i'&time==`t'
drop temp
}
}

William
*
*   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/
```
```
Dr Keith B.G. Dear
Senior Fellow in Biostatistics
National Centre for Epidemiology and Population Health
Australian National University
Canberra, ACT 0200, Australia
Tel: 02 612 54865, Fax: 02 612 50740
http://nceph.anu.edu.au/Staff_Students/staff_pages/dear.php
CRICOS provider #00120C

http://canberragliding.org/

*
*   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/
```