Reputation: 10102
I would like to read off Stata matrix elements by column name so that I can loop over a varlist
after running a regression.
In the following code it works sometimes, but not all the time. And I can't figure out why.
sysuse auto, clear
scalar drop _all
matrix drop _all
regress price weight headroom trunk
matrix b = e(b)
local colnames : colnames b
foreach v of local colnames {
if ("`v'" != "_cons") {
display "-------------------------"
display "`v'"
quietly summarize `v', detail
scalar beta = b[1,`v']
scalar p75 = `r(p75)'
scalar p25 = `r(p25)'
scalar iqr = p75 - p25
scalar effect = beta * iqr
scalar dir
}
}
It fails for weight
and trunk
, but not headroom
. Both weight
and trunk
are negative, but in my own separate code it fails for positive coefficients.
Using a manual counter works (below), but why does it fail with column names? Is there another solution?
regress price weight headroom trunk
matrix b = e(b)
local colnames : colnames b
local i = 1
foreach v of local colnames {
if ("`v'" != "_cons") {
display "-------------------------"
display "`v'"
quietly summarize `v', detail
scalar beta = b[1,`i']
local ++i
scalar p75 = `r(p75)'
scalar p25 = `r(p25)'
scalar iqr = p75 - p25
scalar effect = beta * iqr
scalar dir
}
}
Upvotes: 0
Views: 3014
Reputation:
See help matrix subscripting
for an explanation of why your attempt at subscripting using column names didn't work. Replacing your line with
scalar beta = b[1,colnumb(b,"`v'")]
does work.
Upvotes: 4