Hello all,

This is my first time asking a question on here, so please excuse me if I am describing my issue in a wrong way. I use the version 14.2 and I am relatively new to Stata.
My problem is that when I run this code, I get the error message "SALESGR not found r(111)" even though the variable exists in my dataset as a float variable. If I try this with any other variable I get the same error message.
I work with an unbalanced panel datasset. The idea of this code is to calculate the mean values of SALESGR over the last 3 years. If one of the years is missing it should calculate the mean value of the 2 years available. If only one of the years is available then it should just take the value of the available year. Do you know what could be the problem? Many thanks in advance!

The code:


Code:
// Set the panel structure of the data
xtset ISIN_ID Year

// Create a new variable to store the mean value of SALESGR from _n to _n-2
generate SALESGR_mean = .

// Loop over all panel units
forvalues i = 1/`=_N' {
  // Check if SALESGR is missing in _n, _n-1, and _n-2 for the current panel unit
  if SALESGR[_n, `i'] == . & SALESGR[_n-1, `i'] == . & SALESGR[_n-2, `i'] == . {
    // If SALESGR is missing in all of these years, set SALESGR_mean to .
    replace SALESGR_mean = . in `i'
  } 
  else if SALESGR[_n, `i'] == . & SALESGR[_n-1, `i'] == . {
    // If SALESGR is missing in _n and _n-1, take the mean of _n-2
    replace SALESGR_mean = SALESGR[_n-2, `i'] in `i'
  } 
  else if SALESGR[_n, `i'] == . {
    // If SALESGR is missing in _n, take the mean of _n-1 and _n-2
    replace SALESGR_mean = (SALESGR[_n-1, `i'] + SALESGR[_n-2, `i']) / 2 in `i'
  } 
  else {
    // If SALESGR is present in _n, take the mean of _n, _n-1, and _n-2
    replace SALESGR_mean = (SALESGR[_n, `i'] + SALESGR[_n-1, `i'] + SALESGR[_n-2, `i']) / 3 in `i'
  }
}