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]

st: Average of last two previous observations conditional on another variable value


From   Irene Ferrari <[email protected]>
To   [email protected]
Subject   st: Average of last two previous observations conditional on another variable value
Date   Mon, 24 Mar 2014 14:15:53 +0100

Dear Statalisters,

I am a new statalister and I would greatly appreciate if you could
give me advice on something which seems trivial to explain, less
trivial to translate in Stata code.

I have a panel dataset, and I would like to perform the average
(variable "average") of the last two previous in time observations of
"y" whose corresponding dummy variable ("dummy") is equal to 1.

Example:

--------------------------------------------------------------
id      year      dummy      y        average
1      1990         0           10           .
2      1991         0           11           .
3      1992         1           12           .
4      1993         1           13           .
5      1994         0           14          12.5
6      1995         0           15          12.5
7      1996         1           16          12.5
8      1997         1            17         14.5
9      1998         1            18         16.5
10    1999          0           19          17.5
--------------------------------------------------------------

So, for example, when computing the average for year 1996, I need the
programme to search back the two previous y such that the
corresponding dummy is equal to 1, which are y==12 and y==13, and then
compute the average.

Here is the latest code (of many) I was trying, with no success (it
seems stuck in an infinite loop...):

replace average = .
local k=1
local r=0
local N = _N
local z=1
forvalues i = 1/`N' {
                    while `k'<=2 {
                          if dummy[`i'-`z'] == 1 {
                                                            local r=
`r'+ y[`i'-`z']
                                                   local k=`k'+1
                                                   local z=`z'+1
}
                           else {
                                                       local z=`z'+1
}
}
   replace average=(`r'/2) in `i'
   local k=1
            local r=0
            local z=1
}


I have never needed to perform complicated programming in Stata, so it
is totally possible I am missing something obvious.
Thanks for your consideration.


Irene Ferrari
PhD Student - Department of Economics
University of Bologna
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


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