Bookmark and Share

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]

Antwort: st: Calculating moving windows over time with conditions


From   Johannes Geyer <[email protected]>
To   [email protected]
Subject   Antwort: st: Calculating moving windows over time with conditions
Date   Fri, 4 Feb 2011 13:16:36 +0100

I would use Stata's time-series functions (the lag operator "l."):

********************************
clear
set obs 99
gen id = floor(_n/10)
bys id: gen year = _n + 1800
gen somevar = round(uniform()*100)

xtset id year
gen threeyearsum = somevar + l.somevar + l2.somevar
********************************

But note: if l.somevar, for example, is missing, it results in a missing sum.

best,

johannes



----------------------
Johannes Geyer
Deutsches Institut für Wirtschaftsforschung (DIW Berlin)
German Institute for Economic Research
Department of Public Economics
DIW Berlin
Mohrenstraße 58
10117 Berlin
Tel: +49-30-89789-258

[email protected] schrieb: -----

An: [email protected]
Von: [email protected]
Gesendet von: [email protected]
Datum: 04.02.2011 12:35PM
Thema: st: Calculating moving windows over time with conditions

Dear statalist.

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) ;

Any help or input would be very much appreciated.

Thanks.
Erik.
*
*   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/



© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index