Hello everyone,

I'm having trouble with a loop when trying to use the command outreg2 to extract the results of a decomposition analysis.

Code:
levelsof year, local(levels) 

global X "age sex" 

foreach l of local levels { 
    
    conindex y if year==`l', rankvar(x) truezero keeprank(rank`l') svy 
    scalar CI_`l'=r(CI)
    
    sum y [fw=fweight] if year==`l'
    scalar m_y`l'=r(mean)

    svy: reg y $X if year==`l'
      foreach x of global X {
        
        sca b_`x'`l' = _b[`x'] 

        corr rank`l' `x' [fw=fweight] if year==`l', c
        sca cov_`x'`l' = r(cov_12)            
        sum `x' [fw=fweight] if year==`l'
        
        sca elas_`x'`l' = (b_`x'`l'*r(mean))/m_y`l'        
        sca CI_`x'`l' = 2*cov_`x'`l'/r(mean)            
        sca con_`x'`l' = elas_`x'`l'*CI_`x'`l'            
        sca prcnt_`x'`l' = (con_`x'`l'/CI_`l')*100        

}
    sca residual`l' = CI_`l'
    foreach x of global X {
    sca residual`l'=residual`l'-con_`x'`l'
}
    sca prcnt_res_`l' = (residual`l'/CI_`l')*100

outreg2 using Decomposition.xls, append ctitle(`l') noparen se dec(4) addstat(CI, CI_`l', Elasticity `x', elas_`x'`l', Concentration index `x', CI_`x'`l', Absolute contribution `x', con_`x'`l', Relative contribution `x', prcnt_`x'`l', Residual absolute contribution, residual`l', Residual relative contribution, prcnt_res_`l')
}
This code gives me an error
HTML Code:
elas_2005 not found r(111);
. I know I should loop the command outreg with global X, but every try I've made resulted in having two columns for each year (i.e. the number of X's) in the output excel. Is there a way to avoid this?

I would really appreciate any help

Regards
Thanos