Hello,

I am working on a balanced panel data set whose example is shown below. I want to take yearly average of the variables A and B (seperately) and for each nace2. But my aim is to take average of the last four years, for example for the nace2 variable '51' and year '2013': the average for A should only include the years 2010-2011-2012 and 2013. Moreover, should I handle with missing values seperately? I tried this code but it did not work:

foreach var of varlist A B {
by nace2: egen `var'_avg=mean(`var') if inrange(year,year[_n-4],year[_n])
}

Thank you for your contributions.

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input int(year nace2) float(A P)
2009 51 1461.2297  .010234712
2010 51 2060.3274  .011217712
2011 51 1631.6633  .009138515
2012 51         .  .009079802
2013 51  219.1862  .014016564
2014 51 273.92587   .01216662
2015 51  270.4855  .014872827
2009 52  2700.143  .013527314
2010 52  8844.973  .013993295
2011 52   15835.6  .014242434
2012 52  9403.576   .01332812
2013 52  12200.78  .012611322
2014 52  8156.921  .015147976
2015 52  5486.392  .013481406
2009 61  14059968  .012168975
2010 61   9527888  .006494127
2011 61  12027033  .003669558
2012 61   5539147  .003874143
2013 61   2201740 .0041708336
2014 61 4383958.5  .005500489
2015 61  18545630  .009940005
2009 62   3454367  .017328385
2010 62 2562616.5  .016870743
2011 62   6055793  .011037342
2012 62  946574.3           .
2013 62 189954.63           .
2014 62  423862.8           .
2015 62         0           .
2009 71         0  .007502351
2010 71         0  .010514058
2011 71         0  .006451322
2012 71  393.2239  .006296175
2013 71 12818.802  .007285675
2014 71 21111.506  .011580366
2015 71 33907.652  .009038523
end