I work with panel data which contain several companies (id
) and cover the period from 1.1.2008 to 1.1.2013 (date
, year
). I want to generate new variable (sum1
) which contains a sum of daily observation for var1
for each company and specific time interval. If the interval was equal to each year I would use the function total()
:
bysort id year: egen sum1=total(var1)
In my case however, the time interval is determined as an interval between two events. I have a special variable called event
, which takes value of 1 if the event has occurred on special date and missing otherwise. There are 5 to 10 events for each company. The intervals between events are not equal; hence the first interval can contain 60 observations, the next interval 360 observations. The intervals are also not equal for different companies. The starting date for the first interval for each company is 1.1.2008. The starting date for the second interval is the date of the first event + 1 day. Besides I would like to account for missing values, so if all values of var1
for the company x are missing variable, sum1
for company x and specific interval must contain missing values and not 0.
My panel looks like this:
id date year var1 event sum1(to gen) event_id(to gen)
1 1.1.2008 2008 25 . 95 (25+30+40) 1
1 2.1.2008 2008 30 . 95 (25+30+40) 1
...........................................................1
1 31.4.2008 2008 40 1 95 (25+30+40) 1
1 1.5.2008 2008 50 . 160 (50+50+60) 2
1 2.5.2008 2008 50 . 160 (50+50+60) 2
......................................... ................2
1 31.4.2009 2009 60 1 160 (50+50+60) 2
2 1.1.2008 2008 26 . 96 (26+30+40) 1
2 2.1.2008 2008 30 . 96 (26+30+40) 1
...........................................................1
2 31.6.2008 2008 40 1 96 (26+30+40) 1
2 1.5.2008 2008 51 . 161 (51+50+60) 2
2 2.5.2008 2008 50 . 161 (51+50+60) 2
...........................................................2
2 31.6.2009 2009 60 1 161 (51+50+60) 2
I tried to write different loops (while
, if
), but I failed to do it correctly. I cannot use rolling
as my intervals are not the same.
My other idea was to create the group identifier first (called event_id
), which contains the event_id
for each interval and each company. Then I could use bysort id event_id: egen sum1=total(var1)
, but unfortunately I do not have any idea how to do that. So, the variables event_id
and sum1
in my panel do not exist and serve as an example for output I want to achieve.