I don't know if I got what you mean, but as far as I know your proposal
using -summarize, meanonly- would lead to the average (across the most
recent three years) of the mean (across observations within each year).

But I want to get the average (across the most recent three years) of the
median (across observations within each year), i.e.
average1997=(median1997+median1996+median1995)/3

Not sure what you are doing with all those -locals-. Just -summarize,
meanonly- with your -if- statements and type -ret li- afterwards. There
you
will find the average as r(mean) to plug into your -replace- operation.
HTH