Good morning,

At the moment I need to calculate the average of the 3 previous nmfp for each horse.

The command ...

bysort horse (obs_no) : gen LR3 = (nmfp[_n-1] + nmfp[_n-2] + nmfp[_n-3]) / 3

....achieves this but creates a problem in rows 1-3 as there are not 3 previous observations.

How can I amend the formula to calculate the average nmfp for the previous 2 or 1 or no previous observations, if 3 previous observations do not exist?

Thank you,
Hans

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str16 race_time str14 horse long obs_no float(nmfp LR3)
"30/09/2014 14:00" "Primo Capitano" 207640  .4548          .
"25/10/2014 13:55" "Primo Capitano" 216342  .2582          .
"28/11/2014 12:15" "Primo Capitano" 226747 -.5222          .
"16/03/2015 15:10" "Primo Capitano" 252322 -.5222      .0636
"04/06/2015 20:05" "Primo Capitano" 280266  .0727 -.26206666
"03/07/2015 17:30" "Primo Capitano" 290791 -.2582     -.3239
"02/09/2015 15:40" "Primo Capitano" 312979 -.5164     -.2359
end