Search code examples
variableslabelnaming-conventionsstata

How to get variable labels of regression output in matrix


In Stata, say that I have these data:

sysuse auto2, clear
gen name = substr(make, 1,3)
encode name, gen(name2) 

I run this regression, which importantly uses i.:

reg price i.name2 trunk weight turn

The output takes the form of:

------------------------------------------------------------------------------
       price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       name2 |
        Aud  |   4853.048   1254.083     3.87   0.000     2331.545    7374.551
        BMW  |   5742.124   1560.161     3.68   0.001     2605.211    8879.037
        Bui  |   1351.065    946.733     1.43   0.160    -552.4696    3254.599
        Cad  |   7740.865   1168.332     6.63   0.000     5391.776    10089.95
        Che  |   62.35577   946.1153     0.07   0.948    -1839.937    1964.648
....

I then go to the estimation results:

matrix list e(b)

which produces:

e(b)[1,27]
            1b.          2.          3.          4.          5.          6.          7.
         name2       name2       name2       name2       name2       name2       name2
y1           0   4853.0482   5742.1237   1351.0647   7740.8653   62.355771   2676.3971

             8.          9.         10.         11.         12.         13.         14.
         name2       name2       name2       name2       name2       name2       name2
y1    943.4266   1964.8242   1776.4058   2711.4324   6386.7936 
....

My question is how can I retrieve the variable labels from the name2 variable after the regression is run? What I want is what is displayed in the initial output: Aud, BMW, Bui, etc. I do not want what is stored in the e(b) matrix: 1b. name2, 2. name2, 3. name2, etc. Is there a way to get what I want stored in e(b) or is is stored elsewhere in other estimation results? Can estout/esttab? I would like to get the results stored in a matrix.


Solution

  • You can store e(b) in a matrix, get the names of your variable with the levelsof command and rename the column names.

    sysuse auto2, clear
    gen name = substr(make, 1,3)
    encode name, gen(name2) 
    
    reg price i.name2 trunk weight turn
    mat A = e(b)
    
    levelsof name, local(names)
    local colnames "`names' trunk weight turn _cons"
    matrix colnames A = `colnames'
    matrix list A