Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stata: convert a matrix to dataset without losing names

Tags:

stata

This question has been asked before but the answers do not seem to apply here. I would like to make a dataset from my regression output, without losing information. Consider:

clear *
input str3 iso3 var1 var2 var3
GBR    10 13 15
USA    9 7 4
FRA    8 8 7
BEL    3 4 5
end

local vars var2 var3
reg var1 var2 var3
matrix A=r(table)
matrix list A

clear
xsvmat A, names(col) norestore

Where Stata complains about the _cons column. I'm not interested in this column (although I also don't understand why it is such a problem to include it) but I don't find an option to cope with this in the xsvmat, svmat or svmat2 help.

like image 221
Jakob Avatar asked Nov 07 '25 19:11

Jakob


1 Answers

Although Stata variable names can usually start with an underscore _, [U] 11.3 Naming conventions explains that _cons is a reserved name, and they can't be used as variable names.

I think you want this:

clear
set more off

input ///
str3 iso3 var1 var2 var3
GBR    10 13 15
USA    9 7 4
FRA    8 8 7
BEL    3 4 5
end

local vars var2 var3
reg var1 var2 var3

matrix A = r(table)

// get original row names of matrix (and row count)
local rownames : rowfullnames A
local c : word count `rownames'

// get original column names of matrix and substitute out _cons
local names : colfullnames A
local newnames : subinstr local names "_cons" "cons", word

// rename columns of matrix
matrix colnames A = `newnames'

// convert to dataset
clear
svmat A, names(col)

// add matrix row names to dataset
gen rownames = ""
forvalues i = 1/`c' {
    replace rownames = "`:word `i' of `rownames''" in `i'
}

// check
order rownames
list, sep(0)

Extended macro functions are used. See help extended_fcn if you're not familiar with them.

See also this answer, which is very similar, and suggests postfile and statsby.

Finally, check ssc describe estout, if your goal is to output regression tables.

like image 193
Roberto Ferrer Avatar answered Nov 12 '25 04:11

Roberto Ferrer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!