Modify allpossible stata ado file , so it accepts any number of variables - stata

I am trying to use allpossible.ado to examine the interactions between several variables. It does not accept more than 6 variables. is there a way to modify the code so it accepts any number of variables.
This is the code, This module was written by Nicholas J. Cox
program define allpossible
version 7.0
* process syntax
gettoken cmd 0 : 0
syntax varlist(min=2 numeric ts) [aw fw iw pw] [if] [in] , /*
*/ [ ECLASS(str) RCLASS(str) NPMAX(int -1) * Format(str) /*
*/ CELLWidth(int 12) Detail ]
marksample touse
qui count if `touse'
if r(N) == 0 {
error 2000
}
if "`eclass'`rclass'" == "" {
di as err "must specify at least one of eclass() or rclass()"
exit 198
}
if "`rclass'" != "" {
local nr : word count `rclass'
if `nr' < 2 {
di as err "rclass() invalid"
exit 198
}
tokenize `rclass'
local rprog "qui `1'"
mac shift
local rclass `*'
}
tokenize `varlist'
local response `1'
macro shift
local rest `*'
local np : word count `rest'
local npmax = cond(`npmax' > 0 , min(`npmax',`np', 6), `np')
local nfits = 0
forval i = 0 / `npmax' {
local nfits = `nfits' + comb(`np',`i')
}
qui count
if r(N) < `nfits' {
di as err "sorry: # of observations should be at least `nfits'"
exit 198
}
* wire in response and apply any weights
local cmd "`cmd' `response'"
if "`detail'" != "" {
local cmd "noisily `cmd'"
}
local etc "[`weight' `exp'] if `touse', `options'"
* main loop, except that we break out somewhere before repetition
qui while 1 {
* no predictors
`cmd' `etc'
foreach s of local eclass {
tempvar v`s'
gen double `v`s'' = e(`s') in 1
label var `v`s'' "`s'"
local results "`results'`v`s'' "
}
if "`rclass'" != "" {
`rprog'
foreach s of local rclass {
tempvar v`s'
gen double `v`s'' = r(`s') in 1
label var `v`s'' "`s'"
local results "`results'`v`s'' "
}
}
tempvar predictors model
gen str6 `predictors' = "(none)" in 1
label var `predictors' "predictors"
gen byte `model' = _n
label var `model' "model"
* one predictor
local p = 1
qui forval i = 1 / `np' {
`cmd' ``i'' `etc'
local p = `p' + 1
foreach s of local eclass {
replace `v`s'' = e(`s') in `p'
}
if "`rclass'" != "" {
`rprog'
foreach s of local rclass {
replace `v`s'' = r(`s') in `p'
}
}
replace `predictors' = "`i'" in `p'
}
if `npmax' == 1 {
continue, break
}
* two predictors
local npm1 = `np' - 1
qui forval i = 1 / `npm1' {
local j1 = `i' + 1
forval j = `j1' / `np' {
local p = `p' + 1
`cmd' ``i'' ``j'' `etc'
foreach s of local eclass {
replace `v`s'' = e(`s') in `p'
}
if "`rclass'" != "" {
`rprog'
foreach s of local rclass {
replace `v`s'' = r(`s') in `p'
}
}
replace `predictors' = "`i' `j'" in `p'
}
}
if `npmax' == 2 {
continue, break
}
* three predictors
local npm2 = `np' - 2
qui forval i = 1 / `npm2' {
local j1 = `i' + 1
forval j = `j1' / `npm1' {
local k1 = `j' + 1
forval k = `k1' / `np' {
local p = `p' + 1
`cmd' ``i'' ``j'' ``k'' `etc'
foreach s of local eclass {
replace `v`s'' = e(`s') in `p'
}
if "`rclass'" != "" {
`rprog'
foreach s of local rclass {
replace `v`s'' = r(`s') in `p'
}
}
replace `predictors' = "`i' `j' `k'" in `p'
}
}
}
if `npmax' == 3 {
continue, break
}
* four predictors
local npm3 = `np' - 3
qui forval i = 1 / `npm3' {
local j1 = `i' + 1
forval j = `j1' / `npm2' {
local k1 = `j' + 1
forval k = `k1' / `npm1' {
local l1 = `k' + 1
forval l = `l1' / `np' {
local p = `p' + 1
`cmd' ``i'' ``j'' ``k'' ``l'' `etc'
foreach s of local eclass {
replace `v`s'' = e(`s') in `p'
}
if "`rclass'" != "" {
`rprog'
foreach s of local rclass {
replace `v`s'' = r(`s') in `p'
}
}
replace `predictors' = "`i' `j' `k' `l'" in `p'
}
}
}
}
if `npmax' == 4 {
continue, break
}
* five predictors
local npm4 = `np' - 4
qui forval i = 1 / `npm4' {
local j1 = `i' + 1
forval j = `j1' / `npm3' {
local k1 = `j' + 1
forval k = `k1' / `npm2' {
local l1 = `k' + 1
forval l = `l1' / `npm1' {
local m1 = `l' + 1
forval m = `m1' / `np' {
local p = `p' + 1
`cmd' ``i'' ``j'' ``k'' ``l'' ``m'' `etc'
foreach s of local eclass {
replace `v`s'' = e(`s') in `p'
}
if "`rclass'" != "" {
`rprog'
foreach s of local rclass {
replace `v`s'' = r(`s') in `p'
}
}
replace `predictors' = "`i' `j' `k' `l' `m'" in `p'
}
}
}
}
}
if `npmax' == 5 {
continue, break
}
* six predictors
local npm5 = `np' - 5
quietly forval i = 1 / `npm5' {
local j1 = `i' + 1
forval j = `j1' / `npm4' {
local k1 = `j' + 1
forval k = `k1' / `npm3' {
local l1 = `k' + 1
forval l = `l1' / `npm2' {
local m1 = `l' + 1
forval m = `m1' / `npm1' {
local n1 = `m' + 1
forval n = `n1' / `np' {
local p = `p' + 1
`cmd' ``i'' ``j'' ``k'' ``l'' ``m'' ``n'' `etc'
foreach s of local eclass {
replace `v`s'' = e(`s') in `p'
}
if "`rclass'" != "" {
`rprog'
foreach s of local rclass {
replace `v`s'' = r(`s') in `p'
}
}
replace `predictors' = "`i' `j' `k' `l' `m' `n'" in `p'
}
}
}
}
}
}
if `npmax' == 6 {
continue, break
}
} /* main loop */
* table output
* integers mapped to strings to protect against decimal places
qui foreach v of local results {
capture assert `v' == int(`v')
if _rc == 0 {
tempvar v2
gen str1 `v2' = ""
replace `v2' = string(`v', "%9.0f")
_crcslbl `v2' `v'
local Results "`Results' `v2'"
}
else local Results "`Results' `v'"
}
if "`format'" == "" {
local format "%4.3f"
}
tabdisp `model' in 1 / `p', c(`predictors' `Results') /*
*/ format(`format') cellwidth(`cellwidth')
di
forval i = 1 / `np' {
di as res " `i'" as text "{col 10}``i''"
}
end
I would like to make it able to accept any number of variable.

Related

Why is this regression in Stata not progressing nor returning an error code?

I am running a multi-level logistic regression in Stata on multiple imputed data with the following command:
xi: mi estimate, cmdok post: melogit outcome i.var1 i.var2 i.var3, difficult || id:
I have succeeded in running similar models with the same covariates and different outcomes. These models only take 1 to 2 minutes using my dataset (approx. n=130,000 with n=10 imputations).
For other outcomes, even after many hours, Stata reaches a certain point and is running "something" but I'm not sure what (i.e. the circle in the bottom right is spinning). I used set trace on to check what was happening under the hood (last approx. 100 lines of output below). I'm not familiar with Mata. Stata reaches this point and seemingly doesn't progress any further, but doesn't return an error code and stop the program. Can anyone suggest why Stata is struggling to proceed any further with the regression, or suggest alternatives to avoid this problem? The same issue occurs both with melogit and meglm with a link(logit) and family(binomial).
- syntax name(name=maxmin) [, NEGH TOLerance(numlist ma
> x=1 >=0) LTOLerance(numlist max=1 >=0) NONRTOLerance NRTOLerance(numlist max=1 >=0)
> QTOLerance(numlist max=1 >=0) GTOLerance(numlist max=1 >=0) ITERate(numlist max=1
> >=0) NOTCONCAVE(numlist max=1 >=0) ndami DIFficult HALFSTEPonly DOOPT SEArch(name)
> Repeat(passthru) Bounds(string) SCore(string) noWARNing noCLEAR noLOg DOTs SHOWTOLe
> rance SHOWNRtolerance SHOWSTEP TRace COEFDIffs GRADient HESSian noSKIPline noOUTput
> Level(cilevel) moptobj(string) * ]
- if `:length local nrtolerance' {
= if 0 {
opts_exclusive "nrtolerance() `nonrtolerance'"
}
- if `:length local qtolerance' {
= if 0 {
opts_exclusive "qtolerance() `nonrtolerance'"
}
- opts_exclusive "`nonrtolerance' `shownrtolerance'"
= opts_exclusive " "
---------------------------- begin opts_exclusive ---
- version 8.2
- args opts optname errcode
- local opts `opts'
= local opts
- local n 0
- while `"`opts'"' != "" {
= while `""' != "" {
local ++n
gettoken item`n' opts : opts, bind
}
- if `n' < 2 {
= if 0 < 2 {
- exit
------------------------------ end opts_exclusive ---
- if `:length local shownrtolerance' {
= if 0 {
local showtolerance showtolerance
}
- if "$ML_preserve" != "no" {
= if "no" != "no" {
if `:length local score' {
di as err "May not specify score() option unless" _n
> " a) estimation subsample is the entire data in memory, or" _n " b) you s
> pecify nopreserve option on -ml model- statement (meaning" _n " your evalua
> tion program explicitly restricts itself to obs." _n " for which $" "ML_sam
> p==1."
exit 198
}
preserve
local N = c(N)
quietly keep if $ML_sample
if (`N' != c(N)) {
mata: Mopt_init_regetviews()
}
}
- if `:length local score' {
= if 0 {
SetupScore `"$ML_evaltype"' `"`score'"' $ML_n $ML_dim
local scores "`s(scores)'"
}
- local tropts `log' `dots' `showtolerance' `showstep'
> `trace' `coefdiffs'
= local tropts
- if "`tropts'" != "nolog" {
= if "" != "nolog" {
- local tropts `tropts' `gradient' `hessian'
= local tropts
- if "`skipline'" == "" {
= if "" == "" {
- if "`iterate'" != "0" | `:length local tropts' {
= if "" != "0" | 0 {
- di
- }
- }
- }
- else {
local gradient
local hessian
local nolog nolog
}
- if "`search'" != "off" & "`iterate'" != "0" {
= if "off" != "off" & "" != "0" {
if "`search'" == "quietly" {
local sopts nolog
}
else {
if `:length local tropts' {
if "`tropts'" != "nolog" {
local sopts trace
}
else local sopts nolog
}
}
if "`search'" == "norescale" {
local sopts `sopts' norescale
}
Search `bounds', nopreserve `sopts' `repeat' `maxmin'
}
- tempname value b V iV
- `vv' mata: Mopt_maxmin()
= version 13: mata: Mopt_maxmin()

Export regression results with categorical exposure variables

I would like to run several linear regressions using categorical exposure variables and to output the results to an excel sheet.
The code below works fine when the exposure is continuous. However, for categorical exposures the code only outputs the first row of results rather for ever level of the exposure.
*Code which works for continuous exposures
sysuse auto.dta
describe
summ
postfile temp str40 exp str40 outcome adjusted N beta se lci uci pval using ///
"\test.dta", replace
foreach out in price weight {
foreach exp in i.rep78 {
foreach adjust in 1 {
if `adjust'==1 local adjusted "mpg"
xi: reg `out' `exp' `adjusted'
local N = e(N)
matrix table=r(table)
local beta = table[1,1]
local se = table[2,1]
local lci = table[5,1]
local uci = table[6,1]
local pval=table[4,1]
post temp ("`out'") ("`exp'") (`adjusted') (`N') (`beta') (`se') ///
(`lci') (`uci') (`pval')
}
}
}
postclose temp
use "\test.dta", clear
export excel using "\test.xlsx", firstrow(variables)
The above code only produces one row with estimates for the first level of rep78 when it should produce 4 rows (rep78 is a 5-level categorical variable).
You need to modify your code to save the results from all the relevant columns of r(table):
. reg price i.rep78
. matrix list r(table)
r(table)[9,6]
1b. 2. 3. 4. 5.
rep78 rep78 rep78 rep78 rep78 _cons
b 0 1403.125 1864.7333 1507 1348.5 4564.5
se . 2356.0851 2176.4582 2221.3383 2290.9272 2107.3466
t . .5955324 .85677426 .67841985 .58862629 2.165994
pvalue . .55358783 .39476643 .49995129 .55818378 .03404352
ll . -3303.696 -2483.2417 -2930.6334 -3228.1533 354.5913
ul . 6109.946 6212.7083 5944.6334 5925.1533 8774.4087
df 64 64 64 64 64 64
crit 1.9977297 1.9977297 1.9977297 1.9977297 1.9977297 1.9977297
eform 0 0 0 0 0 0
So, in your code, after matrix table=r(table) you need to have something like:
forvalues i = 1 / `= colsof(r(table)) - 1' {
local beta = table[1,`i']
local se = table[2,`i']
local lci = table[5,`i']
local uci = table[6,`i']
local pval=table[4,`i']
post temp ("`out'") ("`exp'") (`adjusted') (`N') (`beta') (`se') ///
(`lci') (`uci') (`pval')
}
The following works for me:
sysuse auto.dta, clear
describe
summ
postfile temp str40 exp str40 outcome adjusted N beta se lci uci pval using ///
"test.dta", replace
foreach out in price weight {
foreach exp in i.rep78 {
foreach adjust in 1 {
if `adjust'==1 local adjusted "mpg"
reg `out' `exp' `adjusted'
local N = e(N)
matrix table=r(table)
forvalues i = 1 / `= colsof(r(table))-1' {
local beta = table[1,`i']
local se = table[2,`i']
local lci = table[5,`i']
local uci = table[6,`i']
local pval=table[4,`i']
post temp ("`out'") ("`exp'") (`adjusted') (`N') (`beta') ///
(`se') (`lci') (`uci') (`pval')
}
}
}
}
postclose temp
use "test.dta", clear

invalid syntax and program error

forvalue n=1/18 {
if f_3_`n'_==1 {
local i= `0'
local y=`i'+1
gen ownagri_`y' = f123a_`y'_
replace ownagri_`y' = . if f_2_sel_`n' ==1
local i = `i'+1
}
else if f_3_`n'_==2 {
local i= `0'
local y=`i'+1
gen agri_`y' = f126_a1_`n'_
replace agri_`y' = .if f_2_sel_`n' ==1
local i = `i'+1
}
else if f_3_`n'_==3 {
local i= `0'
local y=`i'+1
gen nonagri_`y' = f126_a1_`n'_
replace nonagri_`y' = . if f_2_sel_`n' ==1
local i = `i'+1
}
else if f_3_`n'_==4 {
local i=`0'
local y=`i'+1 {
gen nonagriself_`y' = f128_`n'_
replace nonagriself_`y' = . if f_2_sel_`n' ==1
local i = `i'+1
}
else if f_3_`n'_==5 {
local i=`0'
local y=`i'+1
gen military_`y' = . if f_2_sel_`n' ==1
local i = `i'+1
}}
}
Stata says my command contains invalid syntax and there is program error: code follows on the same line as close brace.
EDIT:
forvalue n = 1/18 {
if f_3_`n'_==1 {
local y1 = 1
gen ownagri_`y1' = f123a_`y1'_
replace ownagri_`y' = . if f_2_sel_`n'_ ==1
local y1 = `y1'+1
}
else if f_3_`n'_==2 {
local y2 = 1
gen agri_`y2' = f126_a1_`y2'_
replace agri_`y2' = . if f_2_sel_`n'_ ==1
local y2 = `y2'+1
}
else if f_3_`n'_==3 {
local y3 = 1
gen nonagri_`y3' = f126_a1_`y3'_
replace nonagri_`y3' = . if f_2_sel_`n'_ ==1
local y3 = `y3'+1
}
else if f_3_`n'_==4 {
local y4 = 1
gen nonagriself_`y4' = f128_`y4'_
replace nonagriself_`y4' = . if f_2_sel_`n'_ ==1
local y4 = `y4'+1
}
else if f_3_`n'_==6 {
local y5 = 1
gen military_`y5' = f129a_`y5'_
replace military_`y5' = . if f_2_sel_`n'_ ==1 ,modify
local y5 = `y5'+1
}
}
I modified the code and the program seems to work, but the results generated seem to be incomplete. The result shows as follow:
(20,070 missing values generated)
(2,194 real changes made, 2,194 to missing)
(19,229 missing values generated)
(1,129 real changes made, 1,129 to missing)
Why?
Specific comments already made:
a. The }} on the next to last line should be } (William Lisowski)
b. Lines like
if f_3_`n'_==1
are evaluated as if
if f_3_`n'_[1] ==1
which is usually not what is wanted. See this FAQ for much more. But this is not a syntax error.
New specific comment:
c. The line
local y=`i'+1 {
has a spurious { that should be removed.
General comments:
A. Throwing a large chunk of code at us without context is poor question style. You're new to this, which is fine, but equally there is accessible advice for you to follow e.g. on good examples.
B. There is no context here on what you are trying to do and no data example. The Statalist advice on how to present data examples in its FAQ carries over to other sites with easy small modifications (e.g. the advice there on delimiters [CODE] and {/CODE] is irrelevant here).
C. There is repeated code in every branch which can be moved, producing this:
local i = `0'
local y = `i'+1
forvalue n = 1/18 {
if f_3_`n'_==1 {
gen ownagri_`y' = f123a_`y'_
replace ownagri_`y' = . if f_2_sel_`n' ==1
}
else if f_3_`n'_==2 {
gen agri_`y' = f126_a1_`n'_
replace agri_`y' = .if f_2_sel_`n' ==1
}
else if f_3_`n'_==3 {
gen nonagri_`y' = f126_a1_`n'_
replace nonagri_`y' = . if f_2_sel_`n' ==1
}
else if f_3_`n'_==4 {
gen nonagriself_`y' = f128_`n'_
replace nonagriself_`y' = . if f_2_sel_`n' ==1
}
else if f_3_`n'_==5 {
gen military_`y' = . if f_2_sel_`n' ==1
}
}
local i = `i'+1
Whether this code is what you want we cannot say, but it looks legal, and it's shorter than your original.

Go, trying to loop date Regex results

Doing a FindAllStringSubmatch regex match including named groups for different date formats. I am having trouble looping results. The commented out conditional makes it work, but not cleanly and it breaks as I add additional matches. I feel like I am approaching it wrong and would like some redirection. thx/
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
text := "12/31/1956 31/11/1960"
reg := []string{`(?P<month>1[12])/(?P<day>\d\d)/(?P<year>19\d\d)`, `(?P<day>\d\d)/(?P<month>1[12])/(?P<year>19\d\d)`}
// Combine them, case ignored
regall := "(?i)" + strings.Join(reg, "|")
myExp := regexp.MustCompile(regall)
match := myExp.FindAllStringSubmatch(text, -1)
fmt.Println("Match", match, len(match))
fmt.Println("Names", myExp.SubexpNames(), len(myExp.SubexpNames()))
for i := 0; i < len(match); i++ {
result := make(map[string]string)
for j, name := range myExp.SubexpNames() {
result[name] = match[i][j]
//if (result["month"] != "" && result["day"] != "" && result["year"] != "") {
fmt.Println(match[i][0],i,j,result["month"] + "/" + result["day"] + "/" + result["year"])
//}
}
}
}
Results in:
Match [[12/31/1956 12 31 1956 ] [31/11/1960 31 11 1960]] 2
Names [ month day year day month year] 7
12/31/1956 0 0 //
12/31/1956 0 1 12//
12/31/1956 0 2 12/31/
12/31/1956 0 3 12/31/1956
12/31/1956 0 4 12//1956
12/31/1956 0 5 //1956
12/31/1956 0 6 //
31/11/1960 1 0 //
31/11/1960 1 1 //
31/11/1960 1 2 //
31/11/1960 1 3 //
31/11/1960 1 4 /31/
31/11/1960 1 5 11/31/
31/11/1960 1 6 11/31/1960
After some rethinking and help from above, with aid of the above answer I came up looping the regex's separately to better handle overlapping named capture groups I came up with this: (posted for benefit of others and any critique is welcome)
package main
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
month_d := `(?P<month>1[012]|0?[1-9])`
month_t := `(?P<month>jan(?:uary|.)?|feb(?:ruary|.)?|mar(?:ch|.)?|apr(?:il|.)?|may(.)|jun(?:e|.)?|jul(?:y|.)?|aug(?:ust|.)?|sep(?:tember|t|t.|.)?|oct(?:ober|.)?|nov(?:ember|.)?|dec(?:ember|.)?)`
day := `(?P<day>3[01]|[12][0-9]|[0]?[1-9])(?:\s)?(?:th|rd|nd|st)?`
year := `(?P<year>(?:19|20)?\d\d)`
sep_d := `[?:/.-]`
sep_t := `[?:,\s]`
text := "fedskjnkvdsj February 6 2004 sdffd Jan 12th 56 1/12/2000 2013/12/1 2099/12/5 1/12/1999 dsfjhfdhj"
regs := []string{
"(" + month_d + sep_d + day + sep_d + year + ")",
"(" + year + sep_d + month_d + sep_d + day + ")",
"(" + day + sep_d + month_d + sep_d + year + ")",
"(" + month_t + sep_t + day + sep_t + year + ")",
"(" + day + sep_t + month_t + sep_t + year + ")",
}
for i := 0; i < len(regs); i++ {
myExp, err := regexp.Compile("(?i)" + regs[i])
if err != nil {
fmt.Printf("There is a problem with your regexp.\n")
return
}
match := myExp.FindAllStringSubmatch(text, -1)
//fmt.Println("Match", match, len(match))
//fmt.Println("Names", myExp.SubexpNames(), len(myExp.SubexpNames()))
for j := 0; j < len(match); j++ {
result := make(map[string]string)
for k, name := range myExp.SubexpNames() {
result[name] = match[j][k]
}
// Fix Month
themonth := strings.ToLower(result["month"])
if len(themonth) == 1 {
themonth = "0" + themonth
}
if len(themonth) >= 3 {
themonth = themonth[0:3]
switch themonth {
case "jan":
themonth = "01"
case "feb":
themonth = "02"
case "mar":
themonth = "03"
case "apr":
themonth = "04"
case "may":
themonth = "05"
case "jun":
themonth = "06"
case "jul":
themonth = "07"
case "aug":
themonth = "08"
case "sep":
themonth = "09"
case "oct":
themonth = "10"
case "nov":
themonth = "11"
case "dec":
themonth = "12"
default:
fmt.Println("Month Error: " + themonth)
os.Exit(2)
}
}
// Day
theday := result["day"]
if len(theday) == 1 {
theday = "0" + theday
}
// Fix Year
theyear := result["year"]
if len(theyear) == 2 {
val_year, err := strconv.ParseInt(theyear,10,0)
if err != nil {
// handle error
fmt.Println(err)
os.Exit(2)
}
if val_year > 50 {
theyear = "19" + theyear
} else {
theyear = "20" + theyear
}
}
date := themonth + "/" + theday + "/" + theyear
fmt.Println(date)
}
}
}

Error:'no variables defined' in stata when using monte carlo simulation

I have written the program below and keep getting the error message that my variables are not defined.
Can somebody plese see where the error is and how I should adapt the code? Really nothing seems to work.
program define myreg, rclass
drop all
set obs 200
gen x= 2*uniform()
gen z = rnormal(0,1)
gen e = (invnorm(uniform()))^2
e=e-r(mean)
replace e=e-r(mean)
more
gen y = 1 + 1*x +1*z + 1*e
reg y x z
e=e-r(mean)
replace e=e-r(mean)
more
gen y = 1 + 1*x +1*z + 1*e
reg y x z
more
return scalar b0 =_[_cons]
return scalar b1=_[x]
return scalar b2 =_[z]
more
end
simulate b_0 = r(b0) b_1 = r(b1) b_2 = r(b2), rep(1000): myreg
*A possible solution with eclass
capture program drop myreg
program define myreg, eclass
* create an empty data by dropping all variables
drop _all
set obs 200
gen x= 2*uniform()
gen z = rnormal(0,1)
gen e = (invnorm(uniform()))^2
qui sum e /*to get r(mean) you need to run sum first*/
replace e=e-r(mean)
gen y = 1 + 1*x +1*z + 1*e
reg y x z
end
*gather the coefficients (_b) and standard errors (_se) from the *regression each time
simulate _b _se, reps(1000) seed (123): myreg
* show the final result
mat list r(table)
* A possible solution with rclass
* To understand the difference between rclass and eclass, see the Stata manual(http://www.stata.com/manuals13/rstoredresults.pdf)
capture program drop myreg
program define myreg, rclass
drop _all
set obs 200
gen x= 2*uniform()
gen z = rnormal(0,1)
gen e = (invnorm(uniform()))^2
qui sum e
replace e=e-r(mean)
gen y = 1 + 1*x +1*z + 1*e
reg y x z
mat output=e(b)
return scalar b0=output[1,3]
return scalar b1=output[1,1]
return scalar b2=output[1,2]
end
simulate b_0=r(b0) b_1=r(b1) b_2=r(b2), rep(1000) seed (123): myreg
return list
*P.S. You should read all the comments as suggested by #Nick to fully understand what I did here. .