Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, is already up and running.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: how to store matrix in a data file

From   Maarten Buis <>
Subject   Re: st: how to store matrix in a data file
Date   Tue, 23 Oct 2012 09:10:15 +0200

On Tue, Oct 23, 2012 at 7:57 AM, rasool.bux wrote:
> I want to store coefficients of each model in a separate data set by running the following code. Is there any solution?
> sysuse auto,clear
> forv i=1/5 {
>        use "$S_FN",clear
>         generate weight2 = weight^2
>         bsample _N
>         stepwise, pr(.2): regress mpg weight weight2 displ gear turn headroom foreign price
>          mat b = e(b)
> }

*---------------------------- begin example -----------------------------
// data preparation
sysuse auto, clear
sum weight, meanonly
gen c_weight = (weight - r(mean))/2000
label var c_weight "weight centered at mean (short tons)"
sum price, meanonly
gen c_price = (price - r(mean))/1000
label var c_price "price centered at mean (1000s $)"
gen c_weight2 = c_weight*c_weight
tempfile orig
save `orig'

// preparations for the loop
tempfile results
tempname b memhold
local vars "c_weight c_weight2 displ gear turn headroom foreign c_price"
postfile `memhold' `vars' using `results'

// k (in this case 20) bootstrap samples
local k = 20
_dots 0, title(Selecting varialbes in bootstrap samples) reps(`k')
forvalues i = 1/`k' {
	// get the bootstrap sample and estimate model
	qui use `orig', clear
	capture stepwise, pr(.2): regress mpg `vars'

	// gives you something to look at while the loop is running
	nois _dots `i' `=_rc'
	// get names of included variables
	matrix `b' = e(b)
	local incl : colnames `b'
	// reset local res to empty
	local res ""
	// a variable gets coefficient if included and missing when not
	foreach var of local vars {
		if `: list var in incl' {
			local res "`res' (_b[`var'])"
		else {
			local res "`res' (.)"
	// post those results
	post `memhold' `res'
postclose `memhold'

// look at the results
use `results', clear
*----------------------------- end example ------------------------------
(For more on examples I sent to the Statalist see: )

Hope this helps,

Maarten L. Buis
Reichpietschufer 50
10785 Berlin
*   For searches and help try:

© Copyright 1996–2015 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index