Saving coefficients and standard errors as variables

18,344

An example to do it manually,

sysuse auto, replace
reg price mpg foreign trunk weight length
mata: b=st_matrix("e(b)")' // extracts e(b) into mata matrix b
mata: se=sqrt(diagonal(st_matrix("e(V)"))) // converts e(V) into se and placed in mata matrix se
getmata b se, force // force mata matrices into variables
list b se if b<.

Or to avoid mata, you could use,

sysuse auto, replace
reg price mpg foreign trunk weight length
ereturn list
mat b=e(b)' // transpose e(b) into matrix b
svmat double b, n(beta) // convert matrix b into variable beta1 (see help svmat)

mat V=e(V) // place e(V) in V
loca nv=`e(rank)' // count number of right hand variables
mat se=J(`nv',1,-9999) // create empty matrix for standard errors
forval i=1/`nv' {
    mat se[`i',1]=sqrt(V[`i',`i']) // convert the variances into the se one at a time
}   
svmat double se, n(se) // convert matrix se into variable se1
list beta1 se1 if beta1<.

Not quite sure how you wanted the values to be arranged. If you like them in columns rather than rows (say you like to manually predict yhat), just transpose the matrices before running svmat. Only these three lines need to be modified.

mat b=e(b) // instead of "mat b=e(b)'"
mat se=J(1,`nv',-9999) // instead of "mat se=J(`nv',1,-9999)"
mat se[1,`i']=sqrt(V[`i',`i']) // instead of "mat se[1,`i']=sqrt(V[`i',`i'])"
Share:
18,344
user3507584
Author by

user3507584

Updated on August 03, 2022

Comments

  • user3507584
    user3507584 over 1 year

    I have run a regression and I would like to save the coefficients and the standard errors as variables.

    I can see the coefficients with ereturn list and e(b) but I have trouble at getting the standard errors. Also, I don't really now how to turn those into variables. In the Stata manual they refer to [eqno] b[varname] and [eqno] se[varname] but there's no example and I can't figure out/find online how to use them.

    Example where b1 is the regression coefficient for dependent variable 1, se1 is regression standard error for dependent var1:

    name    year    output  var1    var2    b1  b2  se1 se2  
    a   1   0.72    0.74    0.87    0.64    0.15    0.48    0.62  
    a   2   0.61    0.75    0.33    0.64    0.15    0.48    0.62  
    a   3   0.08    0.61    0.85    0.64    0.15    0.48    0.62  
    b   1   0.02    0.22    0.26    0.64    0.15    0.48    0.62  
    b   2   0.8 0.32    0.51    0.64    0.15    0.48    0.62  
    b   3   0.47    0.68    0.79    0.64    0.15    0.48    0.62  
    c   1   0.56    0.12    0.63    0.64    0.15    0.48    0.62  
    c   2   0.35    0.49    0.53    0.64    0.15    0.48    0.62  
    c   3   0.93    0.65    0.97    0.64    0.15    0.48    0.62 
    

    Any help would be hugely appreciated!