# st: Count occurrence and duration of states in panel data

 From go.diva@web.de To statalist@hsphsun2.harvard.edu Subject st: Count occurrence and duration of states in panel data Date Sun, 31 May 2009 15:07:15 +0200

```I want to know how often a person has been in a certain state (e.g. state 2) during the past 30 days before the current state. Important is that the current state should not count.

I have data in which the time intervals are not of equal length. And to keep things for the moment simple I defined a variable s2 which takes on the value 1 if the state of interest occurs. The variable res shows my desired results.

clear
input id begin end state s2 res :mylabel , auto
1 12 14 1 . 0
1 15 46 2 1 0
1 47 52 3 . 1
1 59 66 2 1 1
1 70 80 1 . 1
1 81 88 2 1 1
1 89 105 1 . 2
2 14 21 2 1 0
2 55 59 3 . 1
2 61 109 1 . 0
2 110 115 2 1 0
2 116 200 1 . 1
end

I followed some earlier questions at statalist and stata tips 39, 51 on inrange and events in intervals:

gen count = .

local N = _N
qui forval i = 1/`N' {
egen tag = tag(s2) ///
if Id == Id[`i'] & ///
inrange(begin, begin[`i'] - 30, end)
count if tag == 1
replace count = r(N) in `i'
drop tag
}
l, sepby(Id)

I surmise that the inrange command is not appropriate. As s2 should also count if even the begin date has been more than 30 days away but the person is in the state within the 30 day interval (with respect to the end date),

Can inrange be adjusted such that it takes the begin date and the end date into account? Do I have to think about an entirely different approach?

The next step would be to calculate the duration the person has been in s2 during the past 30 days. If there is a related solution I would be extremely happy if you let me know this as well.

Any ideas will be appreciated!
Elke
____________________________________________________________
Text: GRATIS für alle WEB.DE-Nutzer: Die maxdome Movie-FLAT!
Jetzt freischalten unter http://movieflat.web.de

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