You may need to think about in terms of a case that there are no values till the end of your sample period. For example, id 4 from 2004 to 2017. Taking the average of leading and ending non-missing values in a time series of an individual cannot be applied to this scenario. Hope this helpful. Dr. Huang may have a double check the correctness of this code.