Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# Re: st: Calculating rolling averages

 From Nick Cox To statalist@hsphsun2.harvard.edu Subject Re: st: Calculating rolling averages Date Fri, 9 Mar 2012 17:26:52 +0000

```No. The documentation for -egen- does warn against using subscripts in
-egen- calls but that is not the main issue here. The way -if- works
is to select observations and

if date[_n] > date

is just a slightly long-winded way of saying

if date > date

which selects no observations. (Your point that date[1] < date[2] is
no doubt true for your judges but not pertinent to explaining what is
going on here.)  In any case, -egen-'s -mean()- function calculates
means for blocks of observations but otherwise does not respect order
of observations in any sense.

You could just -tsset- in terms of a pseudo-time variable that is the
number of cases so far seen.

Alternatively, if you want the average so far handled that is at its simplest

bysort id (date) : gen mean = sum(offense_9) / _n

but much depends on precisely what the variable is. Any missing values
would require more complicated code.

Nick

On Fri, Mar 9, 2012 at 5:05 PM, William Hauser <whauseriii@gmail.com> wrote:

> I am attempting to calculate the percentage of cases handled by a
> judge that meet some criterion (e.g. being a violent offender).  The
> data cover 13 years so obviously the averages for each judge change
> overtime.  My first thought was the following command:
>
> bysort id date:  egen pct=mean(offense_9) if date[_n]>date
>
> I had hoped that Stata would calculate the average based only on cases
> with a earlier (smaller) date but instead the command results in all
> missing values because date[1]<date[2] and so forth.
>
> Another thought was to use the rolling command (which I'm not sure how
> to do anyways) but this requires the use of tsset.  When I tsset my
> data I get an error, "repeated time values within panel" presumably
> because each judge handles multiple cases a day.
>
> I imagine this is probably a simple matter of syntax but I am in well
> over my head.  Any insight you could provide would be greatly
> appreciated.
>

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