ben
ben

Reputation: 799

In Stata, how do I manipulate matrix elements by their name?

In Stata, after a regression I know it is possible to call the elements of stored results by name. For example, if I want to manipulate the coefficient on the variable precip, I just type _b[precip]. My question is how do I do the same after the tabstat command? For example, say I want to multiply the coefficient on precip by the sample mean of precip:

    reg --variables in regression--
    tabstat --variables in regression--
    mat X=r(StatTotal)
    mat Y=_b[precip]*X[1,precip]

Ah, if only it were that simple. But alas, in the last line X[1, precip] is invalid syntax. Oddly, Stata does recognize display X[1, precip]. And Stata would know what I'm trying to do if instead of precip I used the column number where precip appears in the X vector. If I were just doing this operation once, no problem. But I need to do this operation several times (for several different model specifications) and for several variables which change position in the vector from one model to the next, so I cannot just use the column number.

Upvotes: 0

Views: 3664

Answers (1)

StasK
StasK

Reputation: 1555

I am not yet sure I understand exactly what you want to do, but here's my attempt to reproduce what you are doing:

    sysuse auto, clear
    regress price mpg foreign weight
    tabstat mpg foreign weight, save
    matrix X = r(StatTotal)
    matrix Y = _b[mpg]*X[1, colnumb(X, "mpg") ]

If you need to put this into a cycle, that's doable, too:

    matrix bb = e(b)
    local explvar : colnames bb
    foreach x in `explvar' {
      if "`x'" != "_cons" {
        matrix Y_`x' = _b[`x'] * X[1, colnumb(X, "`x'")]
      }
      else {
        matrix Y_`x' = _b[`x']
      }
    }

You'd probably want to put this into a program that you will call after each regression model estimation call, e.g.:

    program define reg2mat , prefix( name )

      if "`e(cmd)'" != "regress" {
        // this will intentionally produce an error
        regress
      }

      tempname bb

      matrix `bb' = e(b)
      local explvar : colnames `bb'
      foreach x in `explvar' {
        if "`x'" != "_cons" {
          matrix `prefix'_`x' = _b[`x'] * X[1, colnumb(X, "`x'")]
        }
        else {
          matrix `prefix'_`x' = _b[`x']
        }
      }
    end // of reg2mat

At many levels, it is not ideal, as it manipulates with the (global) matrices in Stata memory; most of the time, it is a bad idea, as the programs should only manipulate with objects local to them.

I suspect that what you want to do is addressed, in one way or another, by either omnipowerful margins command, or by an appropriate predict, or by matrix score (which is the low level version of predict). Attributing the effects to a variable only makes sense when your regressors are orthogonal, which only happens in carefully designed and conducted experiments.

Upvotes: 2

Related Questions