# Re: st: egen mean function

 From austin nichols To statalist@hsphsun2.harvard.edu Subject Re: st: egen mean function Date Wed, 17 Aug 2005 20:52:08 -0400

```I assume you have numeric date nd, and compute mean cnv across
individuals as, e.g.
. egen mcnv=mean(cnv), by nd

If you have data on every day, or you don't care if any are missing,
and you really want the prior 7 calendar days, you could start with
. bys nd: gen byte nfirst=(_n!=1)
. sort nfirst nd
. set obs `=_N+7'
. replace nd=0 if nd==.
. g byte s=0
. forval d=1/7 {
replace scnv=max(0,scnv)+ /*
*/    max(0,mcnv[_n-`d']*inrange(nd[_n-`d'],nd-7,nd-1)) if nfirst==0
}
. g byte ccnv=0
. forval d=1/7 {
replace ccnv=ccnv+(mcnv[_n-`d']!=. & inrange(nd[_n-`d'],nd-7,nd-1)!=0)
}
. g m7cnv=scnv/ccnv
. li, noo clean
d      nd   mcnv   scnv   ccnv      m7cnv
.       0      .      0      0          .
.       0      .      0      0          .
.       0      .      0      0          .
.       0      .      0      0          .
.       0      .      0      0          .
.       0      .      0      0          .
.       0      .      0      0          .
26nov2003   16035      6      0      0          .
24aug2004   16307     32      0      0          .
26aug2004   16309     27     32      1         32
27aug2004   16310     30     59      2       29.5
28aug2004   16311     34     89      3   29.66667
29aug2004   16312      5    123      4      30.75
30aug2004   16313     30    128      5       25.6
31aug2004   16314      3    158      6   26.33333
01sep2004   16315     27    129      6       21.5
02sep2004   16316     43    156      7   22.28572
03sep2004   16317     12    172      7   24.57143
04sep2004   16318      2    154      7         22
05sep2004   16319     21    122      7   17.42857
06sep2004   16320     44    138      7   19.71428
07sep2004   16321     26    152      7   21.71428

Though there may be a one-line solution avail after much thought...

On 8/17/05, James Avery <macavery@yahoo.com> wrote:
> Dear all,
>  I would like to create a new variable, prior
> week campaign news volume (PWCNV) that is the mean CNV
> for the prior 7 days. Is it possible to do this with
> the egen mean function or with another egen function?

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```