Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
st: RE: Calculating moving windows over time with conditions
From
Nick Cox <[email protected]>
To
"'[email protected]'" <[email protected]>
Subject
st: RE: Calculating moving windows over time with conditions
Date
Fri, 4 Feb 2011 12:38:35 +0000
Consider also using -rolling- or -mvsumm- (SSC). Writing your own code for problems like this is instructive, but not necessary.
Nick
[email protected]
[email protected]
I have an unbalanced panel dataset in which I need to calculate a 3 year moving window for a variable for each actor in the dataset.
I have already calculated the annual total sum for the variable for each year (var_x). I have tagged individuals by year and removed all observations but one per year.
Now I need to sum the annual totals up for each actor by year in 3 year moving windows. As the dataset is unbalanced, I need to make sure that observation _n-1 is indeed the year before _n, and not several years prior to _n. I don't get it quite right. I use stata 10.
Here is the code so far:
sort id year ;
egen tag_id_year = tag(id year) ;
keep if tag_id_year == 1;
sort id year ;
bysort id year: egen var_3yrs = total(var_x) & total(var_x[_n-1]if year==year[_n-1]+1) & total(var_x[_n-2]if year==year[_n-2]+2) ;
I have also tried:
bysort id year: egen var_3yrs = total(var_x) + total(var_x[_n-1]if year==year[_n-1]+1) + total(var_x[_n-2]if year==year[_n-2]+2) ;
And:
bysort id year: egen var_3yrs = total(var_x + var_x[_n-1]if year==year[_n-1]+1 + var_x[_n-2]if year==year[_n-2]+2) ;
*
* 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/