Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, statalist.org is already up and running.

# Re: st: Loop for creating a sum of previous observations in an unbalanced panal data set

 From Eric Booth To "" Subject Re: st: Loop for creating a sum of previous observations in an unbalanced panal data set Date Fri, 17 Sep 2010 18:47:02 +0000

```<>

Kaspar, here's one solution:

*******************!
clear
//1.  create some fake date data to work with//
set obs 1000
g date = date("01/01/2008", "MDY") in 1
replace date = date[_n-1]+1 in 2/l
format date %td
forval n = 1/3 {
g value`n' =  int(((`n'*50)+1)*runiform())
}

//2. create running sum for prev 90 days for value1 only//
sort date
g sum3m_value1 = .

forval n = 1/`=_N' {
cap drop i`n'
g i`n' = 1 if  date[`n']>=date & (date[`n']-date) <= 90
egen sum3m_value1`n' = total(value1) if i`n'==1
replace sum3m_value1 = sum3m_value1`n' if mi(sum3m_value1)
drop  i`n'
drop sum3m_value1`n'
}
*******************!
```