*! version 2.0.1 29nov2026 *! margeffx: marginal effects after categorical and limited dependent variable models *! margeff-compatible syntax; official -margins- engine with an internal fallback engine *! Author: Dr. Yusuf Toyin Yusuf, Department of Economics and Development Studies, *! Kwara State University, Malete, Nigeria (yusuf.yusuf@kwasu.edu.ng) program define margeffx, eclass version 11 local vcaller = _caller() gettoken first rest : 0, parse(" ,") if `"`first'"' == "replay" { Replay `rest' exit } if `"`first'"' == "selftest" { _mgx_selftest `rest' exit } if `"`first'"' == "compute" { local 0 `"`rest'"' } if replay() { if "`e(cmd)'" == "margeffx" { Replay `0' exit } } else if "`e(cmd)'" == "margeffx" { di as err "the current estimation results were posted by {bf:margeffx, replace};" di as err "re-fit the model before computing new marginal effects" exit 301 } global MGX_VCALLER `vcaller' capture noisily Compute `0' local rc = _rc macro drop MGX_* exit `rc' end /* ========================================================================= */ /* Replay */ /* ========================================================================= */ program define Replay syntax [, Level(cilevel) *] if "`e(cmd)'" != "margeffx" { di as err "results of {bf:margeffx} not found" exit 301 } _mgx_header ereturn display, level(`level') _mgx_footnotes end /* ========================================================================= */ /* Compute: options, inference wrappers, posting and display */ /* ========================================================================= */ program define Compute, eclass syntax [if] [in] [, AT(string) COUNT noDIScrete DUMmies(string) /// EFORM LINK(string) MODel(name) noOFFset /// OUTcome(numlist integer >0) PERcent REPLACE POST /// METHod(string) ELASticity(string) PREDict(string) /// INTeff(varlist numeric min=2 max=2) DSUBpop SUMcheck /// STore(name) SAVing(string) GRAPH GOPTs(string asis) FORCE /// VARs(varlist numeric) MEDiator(varname numeric) Level(cilevel) /// ENGine(string) BY(varname) OVER(varname) SDIFF GENerate(name) /// BOOTstrap REPs(integer 200) SEED(string) BCLuster(varname) /// BSTRata(varname) noDOTS ] if "`e(cmd)'" == "" { error 301 } if "`post'" != "" local replace replace local ismi = ("`e(mi)'" == "mi") if !`ismi' { capture confirm matrix e(b) if _rc { di as err "last estimation results contain no e(b)" exit 301 } } if "`over'" != "" { if "`by'" != "" & "`by'" != "`over'" { di as err "specify only one of by() and over()" exit 198 } local by `over' } if "`sdiff'" != "" & "`by'" == "" { di as err "sdiff requires by() or over()" exit 198 } if `ismi' & "`bootstrap'" != "" { di as err "bootstrap cannot be combined with mi estimate results" exit 198 } if `ismi' & "`generate'" != "" { di as txt "(note: generate() is not available after mi estimate; ignored)" local generate "" } if "`bootstrap'" != "" & `reps' < 50 { di as err "reps() must be at least 50" exit 198 } if "`generate'" != "" & "`by'" != "" { di as txt "(note: generate() stores observation-level effects for the whole sample)" } /* ---------------- model registry and engine ------------------------- */ if `ismi' local cmdx = cond("`model'" != "", "`model'", cond("`e(cmd_mi)'" != "", "`e(cmd_mi)'", "`e(cmd)'")) else local cmdx = cond("`model'" != "", "`model'", "`e(cmd)'") _mgx_registry `cmdx' local reng `r(engine)' local engine = lower("`engine'") if "`engine'" == "" local engine auto if !inlist("`engine'", "auto", "margins", "internal") { di as err "engine() must be auto, margins or internal" exit 198 } if "`engine'" == "auto" local eng0 = cond("`reng'" == "internal", "internal", "margins") else local eng0 `engine' global MGX_ENGINE `eng0' global MGX_NOSE "" global MGX_GENOK "" /* ---------------- options handed to the core ------------------------ */ local coreopts "" foreach o in count discrete eform offset dsubpop force { if "``o''" != "" local coreopts `coreopts' ``o'' } foreach o in at dummies link model outcome method elasticity predict inteff vars mediator { if `"``o''"' != "" local coreopts `"`coreopts' `o'(``o'')"' } tempname B JJ IB IJ V VI PCI DFMI hold Bc Vc local vce delta local nreps 0 local nmiss 0 local Mmi 0 /* ---------------- multiple imputation ------------------------------- */ if `ismi' { _mgx_mi `if' `in', b(`B') v(`V') ib(`IB') vi(`VI') df(`DFMI') by(`by') /// coreopts(`coreopts') local vce mi local Mmi `nmi' } else { marksample touse qui replace `touse' = 0 if !e(sample) capture noisily _mgx_full `if' `in', b(`B') j(`JJ') ib(`IB') ij(`IJ') /// by(`by') coreopts(`coreopts') if _rc { local rc = _rc if "`engine'" == "auto" & "`eng0'" == "margins" & `rc' != 1 { di as txt "(margins could not compute the effects, rc = `rc';" di as txt " switching to the internal engine)" global MGX_ENGINE internal _mgx_full `if' `in', b(`B') j(`JJ') ib(`IB') ij(`IJ') /// by(`by') coreopts(`coreopts') } else exit `rc' } matrix `V' = `JJ' * e(V) * `JJ'' matrix `V' = (`V' + `V'') / 2 if "`inteff'" != "" { matrix `VI' = `IJ' * e(V) * `IJ'' matrix `VI' = (`VI' + `VI'') / 2 } if "`bootstrap'" != "" { _mgx_boot `if' `in', reps(`reps') b(`B') v(`V') ib(`IB') vi(`VI') /// pci(`PCI') by(`by') coreopts(`coreopts') seed(`seed') /// bcluster(`bcluster') bstrata(`bstrata') level(`level') `dots' local vce bootstrap local nreps `bgood' local nmiss `bfail' } } /* ---------------- scaling and stripes ------------------------------- */ local scale = cond("`percent'" != "", 100, 1) matrix `B' = `scale' * `B' matrix `V' = (`scale'^2) * `V' matrix colnames `B' = `stripe' matrix colnames `V' = `stripe' matrix rownames `V' = `stripe' if "`inteff'" != "" { matrix `IB' = `scale' * `IB' matrix `VI' = (`scale'^2) * `VI' matrix colnames `IB' = `istripe' matrix colnames `VI' = `istripe' matrix rownames `VI' = `istripe' } if "`vce'" == "bootstrap" { matrix `PCI' = `scale' * `PCI' matrix colnames `PCI' = `stripe' matrix rownames `PCI' = ll ul } /* ---------------- adding-up check ----------------------------------- */ tempname SB SV L local dosum 0 if "`sumcheck'" != "" { if "`by'" != "" { di as txt "(note: sumcheck is not available with by(); ignored)" } else if !inlist(`group', 2, 4) { di as txt "(note: sumcheck applies only to multiple-outcome models; ignored)" } else if `nout' != `nall' { di as txt "(note: sumcheck requires all outcomes; ignored)" } else { local p : word count `names1' matrix `L' = J(`p', `p' * `nout', 0) forvalues r = 1/`p' { forvalues o = 1/`nout' { matrix `L'[`r', (`o' - 1) * `p' + `r'] = 1 } } matrix `SB' = `B' * `L'' matrix `SV' = `L' * `V' * `L'' matrix colnames `SB' = `names1' matrix colnames `SV' = `names1' matrix rownames `SV' = `names1' local dosum 1 } } /* ---------------- subgroup tests and second differences ------------- */ tempname BT SDB SDV local dobt 0 if "`by'" != "" { _mgx_bytest , b(`B') v(`V') keys(`keys') groups(`groups') t(`BT') /// sdb(`SDB') sdv(`SDV') `sdiff' local dobt 1 } /* ---------------- observation-level effects ------------------------- */ if "`generate'" != "" { _mgx_obsgen , stub(`generate') touse(`touse') names(`names1') types(`types1') /// pspecs(`pspecs') eqs(`eqs1') nout(`nout') setsdef(`setsdef') /// elasticity(`elasticity') scale(`scale') } /* ---------------- titles -------------------------------------------- */ local title "`mtxt' after `cmdlab'" /* ===================================================================== */ /* post, display, store, export */ /* ===================================================================== */ matrix `Bc' = `B' matrix `Vc' = `V' if "`replace'" == "" { _estimates hold `hold', copy restore } if `ismi' { local dfmin = . forvalues c = 1/`=colsof(`DFMI')' { local dfmin = min(`dfmin', `DFMI'[1, `c']) } if `dfmin' >= . | `dfmin' > 1e6 { ereturn post `B' `V', obs(`N') depname(`dv') } else { local dfmin = max(1, floor(`dfmin')) ereturn post `B' `V', obs(`N') depname(`dv') dof(`dfmin') } } else ereturn post `B' `V', esample(`touse') obs(`N') depname(`dv') ereturn local cmd0 "`cmd0'" ereturn local model "`cmdx'" ereturn local title "`title'" ereturn local predlabel `"`mlabel'"' ereturn local atspec `"`=trim("`atlabel'")'"' ereturn local outcomes "`outvals'" ereturn local continuous "`tcont'" ereturn local elastic "`tela'" ereturn local elasticity "`elasticity'" ereturn local factors "`tfac'" ereturn local dummies "`tdum'" ereturn local dsets "`tset'" ereturn local counts "`tcnt'" ereturn local types "`types1'" ereturn local engine "$MGX_ENGINE" ereturn local by "`by'" ereturn local groups "`groups'" if "`dsubpop'" != "" ereturn local dsubpop "dsubpop" ereturn local vce "`vce'" if "`vce'" == "delta" ereturn local vcetype "Delta-method" if "`vce'" == "bootstrap" ereturn local vcetype "Bootstrap" if "`vce'" == "mi" ereturn local vcetype "MI (Rubin)" ereturn local properties "b V" ereturn scalar k_out = `nout' ereturn scalar percent = ("`percent'" != "") if "`vce'" == "bootstrap" { ereturn scalar N_reps = `nreps' ereturn scalar N_misreps = `nmiss' ereturn matrix ci_percentile = `PCI', copy } if "`vce'" == "mi" { ereturn scalar M_mi = `Mmi' matrix colnames `DFMI' = `stripe' ereturn matrix df_mi = `DFMI', copy } if "`inteff'" != "" { ereturn matrix b_inteff = `IB', copy ereturn matrix V_inteff = `VI', copy ereturn local inteff "`x1' `x2'" } if `dosum' { ereturn matrix b_sum = `SB', copy ereturn matrix V_sum = `SV', copy } if `dobt' { ereturn matrix bytest = `BT', copy capture confirm matrix `SDB' if "`sdiff'" != "" & !_rc { ereturn matrix b_sdiff = `SDB', copy ereturn matrix V_sdiff = `SDV', copy } } ereturn local cmd "margeffx" _mgx_header ereturn display, level(`level') _mgx_footnotes if "`vce'" == "bootstrap" { di as txt " bootstrap percentile confidence intervals are stored in e(ci_percentile)" } if "`inteff'" != "" { local ttl "Interaction effect of `x1' and `x2' (average of the cross-partial derivative)" if "`t_x1'`t_x2'" == "dd" local ttl "Interaction effect of `x1' and `x2' (double difference)" _mgx_table , b(`IB') v(`VI') level(`level') title(`"`ttl'"') if "`t_x2'" == "c" { di as txt " (derivative with respect to `x2' by central difference, h = " %9.2e `hstep' ")" } } if `dosum' { _mgx_table , b(`SB') v(`SV') level(`level') /// title("Adding-up check: effects summed over all outcomes (should be 0)") } if `dobt' { _mgx_bytable , t(`BT') by(`by') groups(`groups') capture confirm matrix `SDB' if "`sdiff'" != "" & !_rc { _mgx_table , b(`SDB') v(`SDV') level(`level') /// title("Second differences: effect in group minus effect in reference group") local G : word count `groups' local g1 : word 1 of `groups' forvalues g = 2/`G' { di as txt " d`g' = " as res "`: word `g' of `groups''" as txt " minus " as res "`g1'" } } } if "`store'" != "" { estimates store `store', title("`title'") di as txt "(results stored as {bf:`store'})" } if `"`saving'"' != "" | "`graph'" != "" { _mgx_export , b(`Bc') v(`Vc') level(`level') saving(`saving') /// `graph' gopts(`gopts') title("`title'") } if "`replace'" == "" { _estimates unhold `hold' ereturn matrix mfx_b = `Bc', copy ereturn matrix mfx_V = `Vc', copy if "`inteff'" != "" { ereturn matrix mfx_bi = `IB', copy ereturn matrix mfx_Vi = `VI', copy } if `dosum' ereturn matrix mfx_bsum = `SB', copy di as txt "(original estimation results restored; effects saved in e(mfx_b) and e(mfx_V))" } end /* ========================================================================= */ /* _mgx_full: whole sample or one core run per group of by() */ /* ========================================================================= */ program define _mgx_full, eclass syntax [if] [in] , b(name) j(name) ib(name) ij(name) [ by(string) coreopts(string asis) ] local meta istripe names1 types1 nout nall group cmd0 cmdlab mtxt mlabel atlabel /// tcont tela tfac tdum tset tcnt t_x1 t_x2 hstep x1 x2 outvals dv pspecs eqs1 /// setsdef elasticity if "`by'" == "" { _mgx_core `if' `in', b(`b') j(`j') ib(`ib') ij(`ij') `coreopts' foreach m in `meta' stripe keys N { c_local `m' `"``m''"' } c_local groups "" exit } foreach m in b j ib ij { capture matrix drop ``m'' } marksample touse qui replace `touse' = 0 if !e(sample) tempvar grp qui egen long `grp' = group(`by') if `touse' qui summarize `grp', meanonly local G = r(max) if `G' < 2 | `G' >= . { di as err "by(): `by' must have at least two groups in the estimation sample" exit 198 } tempname tb tjj tib tij local sall "" local kall "" local iall "" local gall "" local Nall 0 forvalues g = 1/`G' { qui levelsof `by' if `grp' == `g', local(lab) clean local gn = strtoname("`by'_`lab'") local gall `gall' `gn' tempvar bt qui gen byte `bt' = `touse' & `grp' == `g' local q = cond(`g' > 1, "quiet", "") if strpos(`"`coreopts'"', "quiet") local q "" _mgx_core if `bt', b(`tb') j(`tjj') ib(`tib') ij(`tij') `coreopts' eqprefix(`gn') `q' matrix `b' = nullmat(`b'), `tb' matrix `j' = nullmat(`j') \ `tjj' capture confirm matrix `tib' if !_rc { matrix `ib' = nullmat(`ib'), `tib' matrix `ij' = nullmat(`ij') \ `tij' } local sall `sall' `stripe' local iall `iall' `istripe' foreach k of local keys { local kall `kall' `g'|`k' } local Nall = `Nall' + `N' } foreach m of local meta { c_local `m' `"``m''"' } c_local stripe `"`sall'"' c_local istripe `"`iall'"' c_local keys `"`kall'"' c_local groups `"`gall'"' c_local N `Nall' end /* ========================================================================= */ /* _mgx_core: all effects for one sample */ /* ========================================================================= */ program define _mgx_core, eclass syntax [if] [in] , b(name) j(name) ib(name) ij(name) [ AT(string) COUNT /// noDIScrete DUMmies(string) EFORM LINK(string) MODel(name) noOFFset /// OUTcome(numlist integer >0) METHod(string) ELASticity(string) /// PREDict(string) INTeff(varlist numeric min=2 max=2) DSUBpop /// VARs(varlist numeric) MEDiator(varname numeric) FORCE EQprefix(string) /// QUIet ] local say = cond("`quiet'" != "", "quietly", "noisily") foreach m in b j ib ij { capture matrix drop ``m'' } local cmd0 `e(cmd)' local cmd = cond("`model'" != "", "`model'", "`e(cmd)'") local cmdlab `cmd0' local depvar `e(depvar)' local dv : word 1 of `depvar' local noff = cond("`offset'" == "nooffset", "nooffset", "") marksample touse qui replace `touse' = 0 if !e(sample) qui count if `touse' local N = r(N) if `N' == 0 error 2000 local mif "" if `"`if'`in'"' != "" local mif `touse' /* ---------------- registry ----------------------------------------- */ _mgx_registry `cmd' local gname `r(group)' local rstat `r(predict)' if "`rstat'" == "." local rstat "" local group 0 if "`gname'" == "binary" local group 1 if inlist("`gname'", "ordered", "multinomial") local group 2 if "`gname'" == "count" local group 3 if "`gname'" == "biprobit" local group 4 if "`gname'" == "cspmed" local group 5 if "`r(found)'" == "0" & "`predict'" == "" { `say' di as txt "(note: `cmd' is not in the model registry; effects refer to the" `say' di as txt " default prediction; add it to margeffx_models_user.txt)" } if "`mediator'" != "" & `group' != 5 { di as err "mediator() is available only after cspmed" exit 198 } /* ---------------- link() / eform ------------------------------------ */ if "`eform'" != "" & "`link'" == "" local link log local expr "" if "`link'" != "" { if inlist(`group', 2, 4, 5) { di as err "link() and eform are not allowed after this model" exit 198 } local xbp predict(xb `noff') if "`link'" == "log" local expr exp(`xbp') else if "`link'" == "logit" local expr invlogit(`xbp') else if "`link'" == "probit" local expr normal(`xbp') else if "`link'" == "cloglog" local expr 1-exp(-exp(`xbp')) else if "`link'" == "identity" local expr `xbp' else { di as err "link() must be one of log, logit, probit, cloglog, identity" exit 198 } } /* ---------------- outcome specifications ---------------------------- */ local nout 0 local nall 1 local outvals "" local eqfilter "" if `group' == 5 { capture which cspmed_p if _rc | "`e(predict)'" != "cspmed_p" { di as err "margeffx needs cspmed 1.2.2 or later (with cspmed_p.ado):" di as err "install the new cspmed files, type -discard-, and re-run cspmed" exit 199 } local cest `e(estimator)' local cmdlab "cspmed (`cest')" if "`mediator'" != "" { local meds `e(mediators)' local pos : list posof "`mediator'" in meds if !`pos' { di as err "mediator(`mediator') is not a mediator of the cspmed model" exit 198 } local lk : word `pos' of `e(mlinks)' local nout 1 local pspec1 predict(mediator(`mediator')) local lab1 = cond("`lk'" == "0", "E(`mediator')", "Pr(`mediator'=1)") local eqfilter `mediator' local group 0 if "`outcome'" != "" `say' di as txt "(note: outcome() ignored with mediator())" } else if "`cest'" == "dml" { di as err "marginal effects are not available after cspmed, estimator(dml)" exit 198 } else if inlist("`cest'", "logit", "probit") { local nout 1 local pspec1 predict(pr) local lab1 "Pr(`dv')" local eqfilter `dv' local group 1 } else if inlist("`cest'", "ols", "iv") { local nout 1 local pspec1 predict(xb) local lab1 "E(`dv')" local eqfilter `dv' local group 0 } else { tempname CT matrix `CT' = e(cats) local K = colsof(`CT') local nall `K' if "`outcome'" == "" { numlist "1/`K'" local outcome `r(numlist)' } foreach i of local outcome { if `i' > `K' { di as err "outcome(`i'): `dv' has only `K' categories" exit 198 } local v = `CT'[1, `i'] local ++nout local pspec`nout' predict(outcome(`v')) local eq`nout' = strtoname("`dv'_`v'") local lab`nout' "Pr(`dv'==`v')" local outvals `outvals' `v' } if inlist("`cest'", "ologit", "oprobit") local eqfilter `dv' else { forvalues k = 2/`K' { local eqfilter `eqfilter' c`k' } } local group 2 } } else if `group' == 2 { qui levelsof `dv' if e(sample), local(vals) local K : word count `vals' local nall `K' if "`outcome'" == "" { numlist "1/`K'" local outcome `r(numlist)' } foreach i of local outcome { if `i' > `K' { di as err "outcome(`i'): `dv' has only `K' categories" exit 198 } local v : word `i' of `vals' local ++nout local pspec`nout' predict(`rstat' `predict' outcome(`v') `noff') local eq`nout' = strtoname("`dv'_`v'") local lab`nout' "Pr(`dv'==`v')" local outvals `outvals' `v' } } else if `group' == 4 { local bip p00 p01 p10 p11 local nall 4 if "`outcome'" == "" local outcome 1 2 3 4 local d2 : word 2 of `depvar' foreach i of local outcome { if `i' > 4 { di as err "outcome() must be in 1/4 after biprobit (p00 p01 p10 p11)" exit 198 } local p : word `i' of `bip' local ++nout local pspec`nout' predict(`p' `noff') local eq`nout' `p' local a = substr("`p'", 2, 1) local c = substr("`p'", 3, 1) local lab`nout' "Pr(`dv'==`a',`d2'==`c')" local outvals `outvals' `p' } } else { if "`outcome'" != "" { `say' di as txt "(note: outcome() ignored; `cmd' has a single prediction)" } local nout 1 local eq1 "" if "`expr'" != "" { local pspec1 expression(`expr') local lab1 "`link'-link prediction: `expr'" } else { local stat "`predict'" if "`stat'" == "" local stat `rstat' if "`stat'`noff'" != "" local pspec1 predict(`stat' `noff') if `group' == 1 local lab1 "Pr(`dv')" else if `group' == 3 local lab1 "E(`dv')" else if "`stat'" != "" local lab1 "predict(`stat')" else local lab1 "default prediction of `cmd'" if "`predict'" != "" local lab1 "predict(`predict')" } } /* ---------------- covariates from e(b) (official parser) ------------ */ _mgx_parsecov , eqfilter(`eqfilter') local allvfull `allv' local fvvfull `fvv' if "`tsv'" != "" { local tsv : list tsv - allv if "`tsv'" != "" { `say' di as txt "(note: time-series-operated terms of `tsv' are not supported and are skipped)" } } if "`vars'" != "" { local allv : list allv & vars local fvv : list fvv & vars local miss : list vars - allvfull if "`miss'" != "" `say' di as txt "(note: `miss' not in the model; ignored)" } if "`allv'" == "" & "`inteff'" == "" { di as err "no covariates found for which marginal effects can be computed" exit 198 } global MGX_FVV `fvvfull' local covs : list allvfull - fvvfull global MGX_COVS `covs' /* ---------------- classify covariates ------------------------------- */ local nonfv : list allv - fvv local contv "" local dumv "" local cntv "" foreach v of local nonfv { qui count if e(sample) & !inlist(`v', 0, 1) local nb = r(N) qui summarize `v' if e(sample), meanonly if `nb' == 0 & r(min) == 0 & r(max) == 1 & "`discrete'" != "nodiscrete" { local dumv `dumv' `v' } else if "`count'" != "" & `nb' > 0 { qui count if e(sample) & `v' != int(`v') if r(N) == 0 local cntv `cntv' `v' else local contv `contv' `v' } else local contv `contv' `v' } /* ---------------- dummy sets ---------------------------------------- */ local nsets 0 local setsdef "" if `"`dummies'"' != "" & "`discrete'" != "nodiscrete" { local rest `"`dummies'"' while `"`rest'"' != "" { gettoken set rest : rest, parse("\") if `"`set'"' == "\" continue if trim(`"`set'"') == "" continue unab set : `set' foreach d of local set { if `: list d in fvvfull' { di as err "dummies(): `d' enters the model as a factor variable;" di as err "factor variables are handled automatically" exit 198 } if !`: list d in allvfull' { di as err "dummies(): `d' is not a covariate of the model" exit 198 } qui count if e(sample) & !inlist(`d', 0, 1) if r(N) { di as err "dummies(): `d' is not a 0/1 variable" exit 198 } } local setsdef `"`setsdef'`set'|"' local set : list set & allv if "`set'" == "" continue local ++nsets local set`nsets' `set' local dumv : list dumv - set local contv : list contv - set local cntv : list cntv - set } } /* ---------------- at() and method() --------------------------------- */ local atstat "" local atvals "" local atvars "" if `"`at'"' != "" { local a : subinstr local at "," " ", all while strpos(`"`a'"', "= ") { local a : subinstr local a "= " "=", all } while strpos(`"`a'"', " =") { local a : subinstr local a " =" "=", all } foreach tok of local a { if inlist("`tok'", "mean", "means") local atstat mean else if inlist("`tok'", "median", "medians") local atstat median else if "`tok'" == "zero" local atstat zero else if strpos("`tok'", "=") { local avar = substr("`tok'", 1, strpos("`tok'", "=") - 1) local aval = substr("`tok'", strpos("`tok'", "=") + 1, .) unab avar : `avar', max(1) confirm number `aval' local atvals `atvals' `avar'=`aval' local atvars `atvars' `avar' } else { di as err "at(): `tok' not allowed" exit 198 } } } if "`method'" != "" { local method = lower("`method'") if inlist("`method'", "mem", "mean", "means") local mstat mean else if inlist("`method'", "median", "medians") local mstat median else if "`method'" == "zero" local mstat zero else if inlist("`method'", "ame", "mer") local mstat "" else { di as err "method() must be ame, mem, median, zero or mer" exit 198 } if "`atstat'" != "" & "`mstat'" != "" & "`atstat'" != "`mstat'" { di as err "method(`method') conflicts with at(`atstat')" exit 198 } if "`mstat'" != "" local atstat `mstat' if "`method'" == "mer" & "`atvals'" == "" { di as err "method(mer) requires at(varname=# ...)" exit 198 } } local atlabel `"`atstat' `atvals'"' local iszero 0 if "`atstat'" == "zero" { local iszero 1 local zvars : list allvfull - fvvfull local zvars : list zvars - atvars foreach z of local zvars { local atvals `atvals' `z'=0 } local atstat "" if "`fvvfull'" != "" { `say' di as txt "(note: at(zero): factor variables `fvvfull' are kept as observed)" } } /* ---------------- elasticity ---------------------------------------- */ if "`elasticity'" != "" { local elasticity = lower("`elasticity'") if !inlist("`elasticity'", "eyex", "dyex", "eydx") { di as err "elasticity() must be eyex, dyex or eydx" exit 198 } } /* ---------------- interaction effect setup -------------------------- */ local x1 "" local x2 "" local t_x1 "" local t_x2 "" local hstep "" if "`inteff'" != "" { local x1 : word 1 of `inteff' local x2 : word 2 of `inteff' foreach x in x1 x2 { if !`: list `x' in allvfull' { di as err "inteff(): ``x'' is not a covariate of the model" exit 198 } if `: list `x' in atvars' { di as err "inteff(): ``x'' may not be fixed in at()" exit 198 } qui count if e(sample) & !inlist(``x'', 0, 1) if r(N) == 0 local t_`x' d else { if `: list `x' in fvvfull' { di as err "inteff(): factor variable ``x'' has more than two levels" exit 198 } local t_`x' c } } if "`t_x2'" == "c" { qui summarize `x2' if e(sample) local hstep = 1e-3 * cond(r(sd) > 0 & r(sd) < ., r(sd), 1) } } /* ===================================================================== */ /* loop over outcomes */ /* ===================================================================== */ tempname tb tj tb2 tj2 bo Jo nb nJ bl Jl local stripe "" local istripe "" local keys "" local types1 "" local names1 "" local pspecs "" local eqs1 "" if `nsets' > 0 & "`dsubpop'" != "" { tempvar sel ssum } forvalues o = 1/`nout' { local ps `pspec`o'' local pspecs `"`pspecs'`ps'|"' local eqo = cond(`nout' > 1, "`eq`o''", "_") local eqs1 `eqs1' `eqo' if "`eqprefix'" != "" { local eqf = cond(`nout' > 1, strtoname("`eqprefix'_`eq`o''"), "`eqprefix'") } else local eqf = cond(`nout' > 1, "`eq`o''", "") capture matrix drop `bo' capture matrix drop `Jo' local onames "" local otypes "" local obases "" _mgx_atspec , stat(`atstat') vals(`atvals') local sp0 `"`r(spec)'"' local atc "" if `"`sp0'"' != "" local atc at(`sp0') /* (a) continuous derivatives and factor-variable contrasts */ local calls "" if "`elasticity'" == "" { local dv1 `contv' `fvv' if "`dv1'" != "" local calls dydx } else { if "`contv'" != "" local calls `elasticity' if "`fvv'" != "" local calls `calls' dydxf } foreach c of local calls { if "`c'" == "dydx" local dl `contv' `fvv' else if "`c'" == "dydxf" local dl `fvv' else local dl `contv' local cop = cond("`c'" == "dydxf", "dydx", "`c'") _mgx_margins , b(`tb') j(`tj') touse(`mif') /// opts(`ps' `cop'(`dl') `atc' `force') local nc = colsof(`tb') forvalues k = 1/`nc' { local cnm : word `k' of `cn' local ceq : word `k' of `ce' local nm `cnm' if regexm("`cnm'", "^[0-9]+\._at$") | "`cnm'" == "_cons" local nm `ceq' if regexm("`nm'", "^[0-9]+b\.") continue if regexm("`nm'", "^[0-9]*o\.") continue if substr("`nm'", 1, 2) == "c." local nm = substr("`nm'", 3, .) local bv `nm' if regexm("`nm'", "\.([^.]+)$") local bv = regexs(1) if `: list bv in fvv' local ty f else local ty = cond("`c'" == "dydx", "c", "e") matrix `bo' = nullmat(`bo'), `tb'[1, `k'] matrix `Jo' = nullmat(`Jo') \ `tj'[`k', 1...] local onames `onames' `nm' local otypes `otypes' `ty' local obases `obases' `bv' } } /* (b) single 0/1 dummies: discrete change 0 -> 1 */ if "`dumv'" != "" { local atl "" foreach d of local dumv { _mgx_atspec , stat(`atstat') vals(`atvals') excl(`d') local atl `atl' at(`r(spec)' `d'=0) at(`r(spec)' `d'=1) } _mgx_margins , b(`tb') j(`tj') touse(`mif') opts(`ps' `atl' `force') local i 0 foreach d of local dumv { local ++i local c0 = 2*`i' - 1 local c1 = 2*`i' matrix `bo' = nullmat(`bo'), (`tb'[1, `c1'] - `tb'[1, `c0']) matrix `Jo' = nullmat(`Jo') \ (`tj'[`c1', 1...] - `tj'[`c0', 1...]) local onames `onames' `d' local otypes `otypes' d local obases `obases' `d' } } /* (c) sets of dummies from one categorical variable */ forvalues s = 1/`nsets' { local set `set`s'' _mgx_atspec , stat(`atstat') vals(`atvals') excl(`set') local sps `"`r(spec)'"' local zero "" foreach d of local set { local zero `zero' `d'=0 } if "`dsubpop'" == "" { local atl at(`sps' `zero') foreach d of local set { local one "" foreach e of local set { local one `one' `e'=`=("`e'" == "`d'")' } local atl `atl' at(`sps' `one') } _mgx_margins , b(`tb') j(`tj') touse(`mif') opts(`ps' `atl' `force') local i 1 foreach d of local set { local ++i matrix `bo' = nullmat(`bo'), (`tb'[1, `i'] - `tb'[1, 1]) matrix `Jo' = nullmat(`Jo') \ (`tj'[`i', 1...] - `tj'[1, 1...]) local onames `onames' `d' local otypes `otypes' s local obases `obases' `d' } } else { capture drop `ssum' qui gen double `ssum' = 0 foreach d of local set { qui replace `ssum' = `ssum' + `d' } foreach d of local set { local one "" foreach e of local set { local one `one' `e'=`=("`e'" == "`d'")' } capture drop `sel' qui gen byte `sel' = `touse' & (`d' == 1 | `ssum' == 0) _mgx_margins , b(`tb') j(`tj') touse(`sel') /// opts(`ps' at(`sps' `zero') at(`sps' `one') `force') matrix `bo' = nullmat(`bo'), (`tb'[1, 2] - `tb'[1, 1]) matrix `Jo' = nullmat(`Jo') \ (`tj'[2, 1...] - `tj'[1, 1...]) local onames `onames' `d' local otypes `otypes' s local obases `obases' `d' } } } /* (d) count variables: unit change x -> x+1 */ if "`cntv'" != "" { local havelevel 0 foreach v of local cntv { local fixed "" foreach t of local atvals { local tv = substr("`t'", 1, strpos("`t'", "=") - 1) if "`tv'" == "`v'" local fixed = substr("`t'", strpos("`t'", "=") + 1, .) } _mgx_atspec , stat(`atstat') vals(`atvals') excl(`v') local spv `"`r(spec)'"' local done 0 if "`fixed'" != "" { _mgx_margins , b(`tb') j(`tj') touse(`mif') /// opts(`ps' at(`spv' `v'=`fixed') at(`spv' `v'=`=`fixed'+1') `force') matrix `bo' = nullmat(`bo'), (`tb'[1, 2] - `tb'[1, 1]) matrix `Jo' = nullmat(`Jo') \ (`tj'[2, 1...] - `tj'[1, 1...]) local done 1 } else if "$MGX_ENGINE" == "margins" & "`atstat'" == "" { /* feature detection: margins at(x=generate()) (newer Stata) */ if "$MGX_GENOK" == "" { capture quietly margins `=cond("`mif'"!="", "if `mif'", "")', /// at((asobserved) _all `v'=generate(`v'+1)) `ps' nose `force' global MGX_GENOK = cond(_rc, "0", "1") } if "$MGX_GENOK" == "1" { _mgx_margins , b(`tb') j(`tj') touse(`mif') opts(`ps' /// at((asobserved) _all `spv') /// at((asobserved) _all `spv' `v'=generate(`v'+1)) `force') matrix `bo' = nullmat(`bo'), (`tb'[1, 2] - `tb'[1, 1]) matrix `Jo' = nullmat(`Jo') \ (`tj'[2, 1...] - `tj'[1, 1...]) local done 1 } } if !`done' { if !`havelevel' { _mgx_margins , b(`bl') j(`Jl') touse(`mif') opts(`ps' `atc' `force') local havelevel 1 } _mgx_shiftrun , var(`v') delta(1) b(`tb') j(`tj') sample(`touse') /// touse(`mif') opts(`ps' `atc' `force') matrix `bo' = nullmat(`bo'), (`tb'[1, 1] - `bl'[1, 1]) matrix `Jo' = nullmat(`Jo') \ (`tj'[1, 1...] - `Jl'[1, 1...]) } local onames `onames' `v' local otypes `otypes' n local obases `obases' `v' } } /* reorder columns to follow the order of the model */ capture matrix drop `nb' capture matrix drop `nJ' local rnames "" local rtypes "" foreach v of local allv { local k 0 foreach bvar of local obases { local ++k if "`bvar'" == "`v'" { matrix `nb' = nullmat(`nb'), `bo'[1, `k'] matrix `nJ' = nullmat(`nJ') \ `Jo'[`k', 1...] local rnames `rnames' `: word `k' of `onames'' local rtypes `rtypes' `: word `k' of `otypes'' } } } capture confirm matrix `nb' if !_rc { matrix `b' = nullmat(`b'), `nb' matrix `j' = nullmat(`j') \ `nJ' foreach nm of local rnames { if "`eqf'" != "" local stripe `stripe' `eqf':`nm' else local stripe `stripe' `nm' local keys `keys' `eqo'|`nm' } if `o' == 1 { local names1 `rnames' local types1 `rtypes' } } /* (e) interaction effect (cross-partial / double difference) */ if "`inteff'" != "" { _mgx_atspec , stat(`atstat') vals(`atvals') excl(`x1' `x2') local spi `"`r(spec)'"' local ati "" if `"`spi'"' != "" local ati at(`spi') if "`t_x2'" == "d" { if "`t_x1'" == "d" { _mgx_margins , b(`tb') j(`tj') touse(`mif') opts(`ps' /// at(`spi' `x1'=0 `x2'=0) at(`spi' `x1'=1 `x2'=0) /// at(`spi' `x1'=0 `x2'=1) at(`spi' `x1'=1 `x2'=1) `force') matrix `tb2' = (`tb'[1, 4] - `tb'[1, 3]) - (`tb'[1, 2] - `tb'[1, 1]) matrix `tj2' = (`tj'[4, 1...] - `tj'[3, 1...]) - (`tj'[2, 1...] - `tj'[1, 1...]) } else { _mgx_margins , b(`tb') j(`tj') touse(`mif') opts(`ps' /// dydx(`x1') at(`spi' `x2'=0) at(`spi' `x2'=1) `force') matrix `tb2' = `tb'[1, 2] - `tb'[1, 1] matrix `tj2' = `tj'[2, 1...] - `tj'[1, 1...] } } else { if "`t_x1'" == "d" local eop at(`spi' `x1'=0) at(`spi' `x1'=1) else local eop dydx(`x1') `ati' local hh = `hstep' / 2 _mgx_shiftrun , var(`x2') delta(`hh') b(`tb') j(`tj') sample(`touse') /// touse(`mif') opts(`ps' `eop' `force') local mh = -`hh' _mgx_shiftrun , var(`x2') delta(`mh') b(`bl') j(`Jl') sample(`touse') /// touse(`mif') opts(`ps' `eop' `force') if "`t_x1'" == "d" { matrix `tb2' = ((`tb'[1, 2] - `tb'[1, 1]) - (`bl'[1, 2] - `bl'[1, 1])) / `hstep' matrix `tj2' = ((`tj'[2, 1...] - `tj'[1, 1...]) - (`Jl'[2, 1...] - `Jl'[1, 1...])) / `hstep' } else { matrix `tb2' = (`tb'[1, 1] - `bl'[1, 1]) / `hstep' matrix `tj2' = (`tj'[1, 1...] - `Jl'[1, 1...]) / `hstep' } } matrix `ib' = nullmat(`ib'), `tb2' matrix `ij' = nullmat(`ij') \ `tj2' local ieq = cond("`eqf'" != "", "`eqf'", "inteff") local istripe `istripe' `ieq':`x1'_X_`x2' } } capture confirm matrix `b' if _rc { di as err "no marginal effects could be computed" exit 498 } /* ---------------- labels returned to the caller --------------------- */ if "`atstat'" == "mean" local mtxt "Marginal effects at means" else if "`atstat'" == "median" local mtxt "Marginal effects at medians" else if `iszero' local mtxt "Marginal effects at zero" else if "`atvals'" != "" local mtxt "Average marginal effects at fixed values" else local mtxt "Average marginal effects" local mlabel "" forvalues o = 1/`nout' { if `nout' > 1 local mlabel `"`mlabel' `eq`o'': `lab`o''|"' else local mlabel `"`lab`o''"' } foreach t in tcont tela tfac tdum tset tcnt { local `t' "" } local k 0 foreach t of local types1 { local ++k local nm : word `k' of `names1' if "`t'" == "c" local tcont `tcont' `nm' if "`t'" == "e" local tela `tela' `nm' if "`t'" == "f" local tfac `tfac' `nm' if "`t'" == "d" local tdum `tdum' `nm' if "`t'" == "s" local tset `tset' `nm' if "`t'" == "n" local tcnt `tcnt' `nm' } foreach m in stripe istripe keys names1 types1 nout nall group cmd0 cmdlab mtxt /// mlabel atlabel tcont tela tfac tdum tset tcnt t_x1 t_x2 hstep x1 x2 outvals /// N dv pspecs eqs1 setsdef elasticity { c_local `m' `"``m''"' } end /* ========================================================================= */ /* coefficient-name parsing with Stata's own parser (_ms_parse_parts), */ /* falling back to pattern matching */ /* ========================================================================= */ program define _mgx_parsecov syntax [, EQfilter(string)] tempname eb matrix `eb' = e(b) local cfn : colfullnames `eb' local allv "" local fvv "" local tsv "" foreach t of local cfn { local eqn "" local nm `"`t'"' local cpos = strpos(`"`t'"', ":") if `cpos' { local eqn = substr(`"`t'"', 1, `cpos' - 1) local nm = substr(`"`t'"', `cpos' + 1, .) } if "`eqfilter'" != "" { if !`: list eqn in eqfilter' continue } /* ancillary parameters: "/" equations (Stata 15+) and xx:_cons (older) */ if substr(`"`eqn'"', 1, 1) == "/" continue if substr(`"`nm'"', 1, 1) == "/" continue if `"`nm'"' == "_cons" continue local pieces : subinstr local nm "#" " ", all local np : word count `pieces' /* names from the official parser */ local offnames "" capture _ms_parse_parts `nm' if !_rc { if inlist("`r(type)'", "variable", "factor") { local offnames `r(name)' } else if inlist("`r(type)'", "interaction", "product") { local kk = r(k_names) forvalues i = 1/`kk' { local offnames `offnames' `r(name`i')' } } } local i 0 foreach p of local pieces { local ++i local pre "" local vn `"`p'"' if regexm(`"`p'"', "^(.*)\.([^.]+)$") { local pre = regexs(1) local vn = regexs(2) } if `: word count `offnames'' == `np' { local on : word `i' of `offnames' capture confirm numeric variable `on' if !_rc local vn `on' } capture confirm numeric variable `vn' if _rc continue if inlist("`pre'", "", "c", "co", "o") { local allv : list allv | vn } else if regexm("`pre'", "^[0-9]+[bno]*$") { local allv : list allv | vn local fvv : list fvv | vn } else { local tsv : list tsv | vn } } } c_local allv `allv' c_local fvv `fvv' c_local tsv `tsv' end /* ========================================================================= */ /* model registry (margeffx_models.txt, margeffx_models_user.txt) */ /* ========================================================================= */ program define _mgx_registry, rclass args cmd local group single local pred "." local eng margins local found 0 local src "" tempname fh foreach f in margeffx_models.txt margeffx_models_user.txt { capture findfile `f' if _rc continue local fn `"`r(fn)'"' file open `fh' using `"`fn'"', read text file read `fh' line while r(eof) == 0 { local line = trim(`"`line'"') if `"`line'"' != "" & substr(`"`line'"', 1, 1) != "*" { local c1 : word 1 of `line' if "`c1'" == "`cmd'" { local group : word 2 of `line' local pred : word 3 of `line' local eng : word 4 of `line' local found 1 local src `f' } } file read `fh' line } file close `fh' } if !`found' { /* built-in fallback, used if the registry file is missing */ local bi probit:binary:pr logit:binary:pr logistic:binary:pr cloglog:binary:pr /// scobit:binary:pr hetprobit:binary:pr hetprob:binary:pr ivprobit:binary:pr /// heckprobit:binary:pmargin heckprob:binary:pmargin xtprobit:binary:pu0 /// xtlogit:binary:pu0 xtcloglog:binary:pu0 ologit:ordered:. oprobit:ordered:. /// gologit:ordered:. gologit2:ordered:. oglm:ordered:. meologit:ordered:. /// meoprobit:ordered:. mlogit:multinomial:. mprobit:multinomial:. /// slogit:multinomial:. biprobit:biprobit:. poisson:count:n nbreg:count:n /// gnbreg:count:n zip:count:n zinb:count:n tpoisson:count:n ztp:count:n /// ztnb:count:n tnbreg:count:n xtpoisson:count:nu0 xtnbreg:count:nu0 /// cspmed:cspmed:.:internal foreach e of local bi { local w : subinstr local e ":" " ", all if "`: word 1 of `w''" == "`cmd'" { local group : word 2 of `w' local pred : word 3 of `w' local e4 : word 4 of `w' if "`e4'" != "" local eng `e4' local found 1 local src built-in } } } if "`pred'" == "" local pred "." if "`eng'" == "" local eng margins return local group "`group'" return local predict "`pred'" return local engine "`eng'" return local found "`found'" return local source "`src'" end /* ========================================================================= */ /* at() specification builder */ /* ========================================================================= */ program define _mgx_atspec, rclass syntax [, stat(string) vals(string) excl(string)] local out "" if "`stat'" != "" local out "(`stat') _all" foreach t of local vals { local vn = substr("`t'", 1, strpos("`t'", "=") - 1) if !`: list vn in excl' local out `out' `t' } return local spec `"`out'"' end /* ========================================================================= */ /* engine dispatcher: official margins, or the internal engine */ /* ========================================================================= */ program define _mgx_margins, eclass syntax , b(name) j(name) [ touse(string) opts(string asis) ] if "$MGX_ENGINE" == "internal" { _mgx_imargins , b(`b') j(`j') touse(`touse') opts(`opts') c_local cn `"`cn'"' c_local ce `"`ce'"' exit } local iff "" if "`touse'" != "" local iff if `touse' local vv = real("$MGX_VCALLER") if missing(`vv') | `vv' < 11 local vv 11 local nose = cond("$MGX_NOSE" == "1", "nose", "") capture noisily version `vv': quietly margins `iff', `opts' `nose' if _rc { local rc = _rc if "$MGX_NOSE" != "1" di as err "margins failed with: margins `iff', `opts'" exit `rc' } matrix `b' = r(b) if "`nose'" != "" { matrix `j' = J(colsof(`b'), colsof(e(b)), 0) } else { capture matrix `j' = r(Jacobian) if _rc { di as err "margins did not return the Jacobian matrix" exit 498 } } local cn : colnames `b' local ce : coleq `b' c_local cn `"`cn'"' c_local ce `"`ce'"' end /* ========================================================================= */ /* internal engine: same input and output as the margins calls used above, */ /* computed with -predict- only; Jacobian by perturbing e(b) */ /* ========================================================================= */ program define _mgx_imargins, eclass syntax , b(name) j(name) [ touse(string) opts(string asis) ] /* split the at() options from the rest */ local s `"`opts'"' local nat 0 local rest "" while `"`s'"' != "" { gettoken tok s : s, bind if lower(substr(`"`tok'"', 1, 3)) == "at(" { local ++nat local at`nat' = substr(`"`tok'"', 4, length(`"`tok'"') - 4) } else local rest `"`rest' `tok'"' } local 0 `", `rest'"' syntax [, PREDict(string) EXPression(string) DYDX(varlist numeric) EYEX(varlist numeric) /// DYEX(varlist numeric) EYDX(varlist numeric) FORCE NOSE ] local spec "" if `"`expression'"' != "" local spec `"expression(`expression')"' else if `"`predict'"' != "" local spec `"predict(`predict')"' local dtype "" local dl "" foreach t in dydx eyex dyex eydx { if "``t''" != "" { local dtype `t' local dl ``t'' } } if `nat' == 0 { local nat 1 local at1 "" } local fvv $MGX_FVV local covs $MGX_COVS tempvar tu qui gen byte `tu' = e(sample) if "`touse'" != "" qui replace `tu' = `tu' & `touse' local wt "" if "`e(wtype)'" != "" & `"`e(wexp)'"' != "" { local wt = cond("`e(wtype)'" == "fweight", "[fw`e(wexp)']", "[aw`e(wexp)']") } /* parse the at() specifications */ local touched `dl' local usemean 0 local usemed 0 forvalues k = 1/`nat' { local stat`k' "" local asg`k' "" local a `"`at`k''"' while `"`a'"' != "" { gettoken tok a : a, bind if substr(`"`tok'"', 1, 1) == "(" { local stat`k' = substr(`"`tok'"', 2, length(`"`tok'"') - 2) } else if strpos(`"`tok'"', "=") { local av = substr(`"`tok'"', 1, strpos(`"`tok'"', "=") - 1) local vv = substr(`"`tok'"', strpos(`"`tok'"', "=") + 1, .) unab av : `av', max(1) confirm number `vv' local asg`k' `asg`k'' `av'=`vv' local touched `touched' `av' } else if `"`tok'"' != "_all" { di as err "internal engine: at() element `tok' not supported" exit 198 } } if "`stat`k''" == "mean" { local usemean 1 local touched `touched' `covs' } else if "`stat`k''" == "median" { local usemed 1 local touched `touched' `covs' } else if !inlist("`stat`k''", "", "asobserved") { di as err "internal engine: at((`stat`k'')) not supported" exit 198 } } local touched : list uniq touched foreach v of local covs { if `usemean' { qui summarize `v' if `tu' `wt', meanonly local mean_`v' = r(mean) } if `usemed' { qui summarize `v' if `tu' `wt', detail local med_`v' = r(p50) } } /* columns */ local ncol 0 local cn "" local ce "" local cn0 : colnames e(b) if "`dtype'" != "" { foreach v of local dl { local isfv : list v in fvv if `isfv' { qui levelsof `v' if e(sample), local(levs) local base "" foreach l of local levs { if `: list posof "`l'b.`v'" in cn0' local base `l' } if "`base'" == "" local base : word 1 of `levs' } else { qui summarize `v' if `tu' local h_`v' = 1e-4 * cond(r(sd) > 0 & r(sd) < ., r(sd), 1) } forvalues k = 1/`nat' { if !`isfv' { local ++ncol local ct`ncol' d local cv`ncol' `v' local ck`ncol' `k' local nm `v' if `nat' > 1 { local cn `cn' `k'._at local ce `ce' `nm' } else { local cn `cn' `nm' local ce `ce' _ } } else { foreach l of local levs { local ++ncol local ct`ncol' f local cv`ncol' `v' local cl`ncol' `l' local cb`ncol' `base' local ck`ncol' `k' local nm = cond("`l'" == "`base'", "`l'b.`v'", "`l'.`v'") if `nat' > 1 { local cn `cn' `k'._at local ce `ce' `nm' } else { local cn `cn' `nm' local ce `ce' _ } } } } } } else { forvalues k = 1/`nat' { local ++ncol local ct`ncol' l local ck`ncol' `k' local cn `cn' `=cond(`nat' > 1, "`k'._at", "_cons")' local ce `ce' _ } } /* back up every variable the engine may change */ local i 0 foreach v of local touched { local ++i local ty`i' : type `v' tempvar ov`i' qui gen double `ov`i'' = `v' qui recast double `v' } tempname b0 V0 bt vrow vplus Jm matrix `b0' = e(b) matrix `V0' = e(V) local kb = colsof(`b0') local npass = cond("`nose'" != "" | "$MGX_NOSE" == "1", 0, 2 * `kb') matrix `Jm' = J(`ncol', `kb', 0) tempvar p1 p0 pc cur ob capture noisily { forvalues pass = 0/`npass' { if `pass' > 0 { local pj = ceil(`pass' / 2) local sg = cond(mod(`pass', 2) == 1, 1, -1) if `V0'[`pj', `pj'] == 0 continue local hb = 1e-5 * max(1, abs(`b0'[1, `pj'])) matrix `bt' = `b0' matrix `bt'[1, `pj'] = `b0'[1, `pj'] + `sg' * `hb' ereturn repost b = `bt' } matrix `vrow' = J(1, `ncol', 0) forvalues c = 1/`ncol' { /* state of the data for this column */ local i 0 foreach v of local touched { local ++i qui replace `v' = `ov`i'' if `tu' } local k `ck`c'' if "`stat`k''" == "mean" { foreach v of local covs { qui replace `v' = `mean_`v'' if `tu' } } if "`stat`k''" == "median" { foreach v of local covs { qui replace `v' = `med_`v'' if `tu' } } foreach a of local asg`k' { local av = substr("`a'", 1, strpos("`a'", "=") - 1) local vv = substr("`a'", strpos("`a'", "=") + 1, .) qui replace `av' = `vv' if `tu' } capture drop `p1' capture drop `p0' capture drop `pc' capture drop `cur' capture drop `ob' if "`ct`c''" == "l" { _mgx_ipred `p1', touse(`tu') spec(`spec') qui summarize `p1' if `tu' `wt', meanonly matrix `vrow'[1, `c'] = r(mean) } else if "`ct`c''" == "d" { local v `cv`c'' local h `h_`v'' qui gen double `cur' = `v' qui replace `v' = `cur' + `h' if `tu' _mgx_ipred `p1', touse(`tu') spec(`spec') qui replace `v' = `cur' - `h' if `tu' _mgx_ipred `p0', touse(`tu') spec(`spec') qui replace `v' = `cur' if `tu' qui gen double `ob' = (`p1' - `p0') / (2 * `h') if `tu' if "`dtype'" != "dydx" { _mgx_ipred `pc', touse(`tu') spec(`spec') if "`dtype'" == "eyex" qui replace `ob' = `ob' * `v' / `pc' if `tu' if "`dtype'" == "dyex" qui replace `ob' = `ob' * `v' if `tu' if "`dtype'" == "eydx" qui replace `ob' = `ob' / `pc' if `tu' } qui summarize `ob' if `tu' `wt', meanonly matrix `vrow'[1, `c'] = r(mean) } else if "`ct`c''" == "f" { if "`cl`c''" != "`cb`c''" { local v `cv`c'' qui gen double `cur' = `v' qui replace `v' = `cl`c'' if `tu' _mgx_ipred `p1', touse(`tu') spec(`spec') qui replace `v' = `cb`c'' if `tu' _mgx_ipred `p0', touse(`tu') spec(`spec') qui replace `v' = `cur' if `tu' qui gen double `ob' = `p1' - `p0' if `tu' qui summarize `ob' if `tu' `wt', meanonly matrix `vrow'[1, `c'] = r(mean) } } } if `pass' == 0 { matrix `b' = `vrow' } else if `sg' == 1 { matrix `vplus' = `vrow' } else { matrix `Jm'[1, `pj'] = ((`vplus' - `vrow') / (2 * `hb'))' } } } local rc = _rc capture ereturn repost b = `b0' local i 0 foreach v of local touched { local ++i qui replace `v' = `ov`i'' qui recast `ty`i'' `v' } if `rc' exit `rc' matrix `j' = `Jm' c_local cn `"`cn'"' c_local ce `"`ce'"' end /* one prediction: predict(...), expression(...) or the default */ program define _mgx_ipred syntax newvarname , touse(varname) [ spec(string asis) ] local s `"`spec'"' if substr(`"`s'"', 1, 8) == "predict(" { local inner = substr(`"`s'"', 9, length(`"`s'"') - 9) if trim(`"`inner'"') == "" qui predict double `varlist' if `touse' else qui predict double `varlist' if `touse', `inner' } else if substr(`"`s'"', 1, 11) == "expression(" { local ex = substr(`"`s'"', 12, length(`"`s'"') - 12) local i 0 while regexm(`"`ex'"', "predict\(([^()]*)\)") { local whole = regexs(0) local inn = regexs(1) local ++i tempvar pv`i' if trim("`inn'") == "" qui predict double `pv`i'' if `touse' else qui predict double `pv`i'' if `touse', `inn' local ex : subinstr local ex "`whole'" "`pv`i''" } qui gen double `varlist' = `ex' if `touse' } else qui predict double `varlist' if `touse' end /* run the engine with one variable shifted by delta, then restore it exactly */ program define _mgx_shiftrun, eclass syntax , var(varname) delta(real) b(name) j(name) sample(varname) /// [ touse(string) opts(string asis) ] local vtype : type `var' tempvar keep qui gen double `keep' = `var' qui recast double `var' qui replace `var' = `var' + `delta' if `sample' capture noisily _mgx_margins , b(`b') j(`j') touse(`touse') opts(`opts') local rc = _rc qui replace `var' = `keep' qui recast `vtype' `var' if `rc' exit `rc' end /* ========================================================================= */ /* bootstrap standard errors */ /* ========================================================================= */ program define _mgx_boot, eclass syntax [if] [in] , reps(integer) b(name) v(name) ib(name) vi(name) pci(name) /// level(cilevel) [ by(string) coreopts(string asis) seed(string) /// bcluster(string) bstrata(string) noDOTS ] local cmdline `"`e(cmdline)'"' if `"`cmdline'"' == "" { di as err "bootstrap needs e(cmdline) to re-fit the model; `e(cmd)' does not store it" exit 198 } if strpos(lower(`"`cmdline'"'), "boot") { di as txt "(note: the model command line contains a bootstrap option; replications may be slow)" } if "`bcluster'" == "" local bcluster `e(clustvar)' local bopts "" if "`bcluster'" != "" local bopts `bopts' cluster(`bcluster') if "`bstrata'" != "" local bopts `bopts' strata(`bstrata') if "`bopts'" != "" local bopts ", `bopts'" local p = colsof(`b') local pi = 0 capture confirm matrix `ib' if !_rc local pi = colsof(`ib') tempname H BB BI bb jj tib tij _estimates hold `H', copy restore preserve if "`seed'" != "" set seed `seed' global MGX_NOSE 1 local good 0 local fail 0 if "`dots'" == "" di as txt _n "Bootstrap replications (" as res `reps' as txt ")" forvalues r = 1/`reps' { restore, preserve qui bsample `bopts' capture quietly `cmdline' local ok = (_rc == 0) if `ok' { capture quietly _mgx_full `if' `in', b(`bb') j(`jj') ib(`tib') ij(`tij') /// by(`by') coreopts(`coreopts' quiet) local ok = (_rc == 0) if `ok' local ok = (colsof(`bb') == `p') } if `ok' { matrix `BB' = nullmat(`BB') \ `bb' if `pi' matrix `BI' = nullmat(`BI') \ `tib' local ++good if "`dots'" == "" di as txt "." _c } else { local ++fail if "`dots'" == "" di as err "x" _c } if "`dots'" == "" & mod(`r', 50) == 0 di as txt " " `r' } if "`dots'" == "" di global MGX_NOSE "" restore _estimates unhold `H' if `good' < 2 { di as err "fewer than two successful bootstrap replications" exit 498 } mata: _mgx_bootv("`BB'", "`v'", "`pci'", `level') if `pi' mata: _mgx_bootv("`BI'", "`vi'", "", `level') if `fail' di as txt "(note: `fail' replications failed and were skipped)" c_local bgood `good' c_local bfail `fail' end /* ========================================================================= */ /* multiple imputation: effects per imputation combined by Rubin's rules */ /* ========================================================================= */ program define _mgx_mi, eclass syntax [if] [in] , b(name) v(name) ib(name) vi(name) df(name) /// [ by(string) coreopts(string asis) ] local cmdline `"`e(cmdline_mi)'"' if `"`cmdline'"' == "" local cmdline `"`e(cmdline)'"' local cmdmi `e(cmd_mi)' if "`cmdmi'" == "" & "`e(cmd)'" != "mi estimate" local cmdmi `e(cmd)' local estcmd "" local s `"`cmdline'"' while strpos(`"`s'"', ":") { local s = substr(`"`s'"', strpos(`"`s'"', ":") + 1, .) local t = trim(`"`s'"') if "`cmdmi'" == "" | substr(`"`t'"', 1, length("`cmdmi'")) == "`cmdmi'" { local estcmd `"`t'"' continue, break } } if `"`estcmd'"' == "" & "`cmdmi'" != "" { local t = trim(`"`cmdline'"') if substr(`"`t'"', 1, length("`cmdmi'")) == "`cmdmi'" local estcmd `"`t'"' } if `"`estcmd'"' == "" { di as err "could not recover the estimation command from e(cmdline)" exit 198 } local mlist `e(m_mi)' if "`mlist'" != "" { numlist "`mlist'" local mlist `r(numlist)' } if "`mlist'" == "" { if "`e(M_mi)'" == "" { di as err "number of imputations not found in e(M_mi)" exit 198 } numlist "1/`e(M_mi)'" local mlist `r(numlist)' } local meta stripe istripe keys names1 types1 nout nall group cmd0 cmdlab mtxt mlabel /// atlabel tcont tela tfac tdum tset tcnt t_x1 t_x2 hstep x1 x2 outvals dv pspecs /// eqs1 setsdef elasticity groups N tempname H BB WS IBB IWS bm jm ibm ijm vm _estimates hold `H', copy restore preserve local M 0 di as txt "Effects in imputation:" _c foreach m of local mlist { restore, preserve quietly mi extract `m', clear capture quietly `estcmd' if _rc { local rc = _rc di as err _n "re-fitting the model failed in imputation `m': `estcmd'" exit `rc' } _mgx_full `if' `in', b(`bm') j(`jm') ib(`ibm') ij(`ijm') by(`by') /// coreopts(`coreopts' quiet) matrix `vm' = `jm' * e(V) * `jm'' matrix `BB' = nullmat(`BB') \ `bm' if `M' == 0 matrix `WS' = `vm' else matrix `WS' = `WS' + `vm' capture confirm matrix `ibm' if !_rc { matrix `IBB' = nullmat(`IBB') \ `ibm' if `M' == 0 matrix `IWS' = `ijm' * e(V) * `ijm'' else matrix `IWS' = `IWS' + `ijm' * e(V) * `ijm'' } local ++M di as txt " `m'" _c } di restore _estimates unhold `H' mata: _mgx_rubin("`BB'", "`WS'", `M', "`b'", "`v'", "`df'") capture confirm matrix `IBB' if !_rc { tempname idf mata: _mgx_rubin("`IBB'", "`IWS'", `M', "`ib'", "`vi'", "`idf'") } foreach m of local meta { c_local `m' `"``m''"' } c_local nmi `M' end /* ========================================================================= */ /* by(): Wald tests of equal effects across groups, second differences */ /* ========================================================================= */ program define _mgx_bytest syntax , b(name) v(name) keys(string) groups(string) t(name) sdb(name) sdv(name) [ sdiff ] local G : word count `groups' local c 0 foreach k of local keys { local ++c local g = substr("`k'", 1, strpos("`k'", "|") - 1) local r = substr("`k'", strpos("`k'", "|") + 1, .) local kl`g' `kl`g'' `r' local kc`g' `kc`g'' `c' } local p = colsof(`b') tempname L d S W Ls Si local trows "" local sstripe "" capture matrix drop `t' capture matrix drop `Ls' foreach r of local kl1 { local i1 : list posof "`r'" in kl1 local c1 : word `i1' of `kc1' local ok 1 forvalues g = 2/`G' { local ig : list posof "`r'" in kl`g' if !`ig' local ok 0 else local cg`g' : word `ig' of `kc`g'' } if !`ok' continue matrix `L' = J(`G' - 1, `p', 0) forvalues g = 2/`G' { matrix `L'[`g' - 1, `cg`g''] = 1 matrix `L'[`g' - 1, `c1'] = -1 } matrix `d' = `L' * `b'' matrix `S' = `L' * `v' * `L'' matrix `Si' = syminv(`S') matrix `W' = `d'' * `Si' * `d' local df = `G' - 1 - diag0cnt(`Si') local chi = `W'[1, 1] local pv = cond(`df' > 0, chi2tail(`df', `chi'), .) matrix `t' = nullmat(`t') \ (`chi', `df', `pv') local eqo = substr("`r'", 1, strpos("`r'", "|") - 1) local nm = substr("`r'", strpos("`r'", "|") + 1, .) local trows `trows' `=cond("`eqo'" == "_", "_", "`eqo'")':`nm' if "`sdiff'" != "" { matrix `Ls' = nullmat(`Ls') \ `L' forvalues g = 2/`G' { local deq = cond("`eqo'" == "_", "d`g'", strtoname("d`g'_`eqo'")) local sstripe `sstripe' `deq':`nm' } } } capture confirm matrix `t' if _rc { matrix `t' = J(1, 3, .) local trows none } matrix colnames `t' = chi2 df p matrix rownames `t' = `trows' if "`sdiff'" != "" { capture confirm matrix `Ls' if !_rc { matrix `sdb' = (`Ls' * `b'')' matrix `sdv' = `Ls' * `v' * `Ls'' matrix `sdv' = (`sdv' + `sdv'') / 2 matrix colnames `sdb' = `sstripe' matrix colnames `sdv' = `sstripe' matrix rownames `sdv' = `sstripe' } } end program define _mgx_bytable syntax , t(name) by(string) groups(string) local G : word count `groups' local rn : rownames `t' local re : roweq `t' di di as txt "Wald tests of equal effects across the `G' groups of `by' (H0: all equal)" di as txt "{hline 34}{c TT}{hline 30}" di as txt _col(35) "{c |}" _col(41) "chi2" _col(51) "df" _col(58) "P>chi2" di as txt "{hline 34}{c +}{hline 30}" local r 0 foreach nm of local rn { local ++r local eq : word `r' of `re' local lab = cond("`eq'" == "_", "`nm'", "`eq': `nm'") local lab = abbrev("`lab'", 32) di as txt %32s "`lab'" _col(35) "{c |}" as res _col(37) %9.3f `t'[`r', 1] /// _col(49) %4.0f `t'[`r', 2] _col(57) %7.4f `t'[`r', 3] } di as txt "{hline 34}{c BT}{hline 30}" end /* ========================================================================= */ /* generate(): observation-level effects */ /* ========================================================================= */ program define _mgx_obsgen syntax , stub(name) touse(varname) names(string) types(string) pspecs(string asis) /// eqs(string) nout(integer) scale(real) [ setsdef(string asis) elasticity(string) ] local wt "" if "`e(wtype)'" != "" & `"`e(wexp)'"' != "" { local wt = cond("`e(wtype)'" == "fweight", "[fw`e(wexp)']", "[aw`e(wexp)']") } local cn0 : colnames e(b) local rest `"`pspecs'"' forvalues o = 1/`nout' { gettoken tok rest : rest, parse("|") if `"`tok'"' == "|" local ps`o' "" else { local ps`o' `"`tok'"' gettoken bar rest : rest, parse("|") } } /* variables that may be changed */ local touched "" foreach nm of local names { local v `nm' if regexm("`nm'", "^[0-9]+\.(.+)$") local v = regexs(1) local touched `touched' `v' } local sr `"`setsdef'"' local nsets 0 while `"`sr'"' != "" { gettoken st sr : sr, parse("|") if `"`st'"' == "|" continue local ++nsets local sdef`nsets' `st' local touched `touched' `st' } local touched : list uniq touched local i 0 foreach v of local touched { local ++i local ty`i' : type `v' tempvar ov`i' qui gen double `ov`i'' = `v' qui recast double `v' } tempvar p1 p0 pc local made "" capture noisily { forvalues o = 1/`nout' { local eqo : word `o' of `eqs' local k 0 foreach nm of local names { local ++k local ty : word `k' of `types' local v `nm' local lev "" if regexm("`nm'", "^([0-9]+)\.(.+)$") { local lev = regexs(1) local v = regexs(2) } local stem = cond(`nout' > 1, "`stub'_`eqo'_`nm'", "`stub'_`nm'") local nv = strtoname("`stem'") confirm new variable `nv' capture drop `p1' capture drop `p0' capture drop `pc' local iv : list posof "`v'" in touched if inlist("`ty'", "c", "e") { qui summarize `v' if `touse' local h = 1e-4 * cond(r(sd) > 0 & r(sd) < ., r(sd), 1) qui replace `v' = `ov`iv'' + `h' if `touse' _mgx_ipred `p1', touse(`touse') spec(`ps`o'') qui replace `v' = `ov`iv'' - `h' if `touse' _mgx_ipred `p0', touse(`touse') spec(`ps`o'') qui replace `v' = `ov`iv'' if `touse' qui gen double `nv' = (`p1' - `p0') / (2 * `h') if `touse' if "`ty'" == "e" { _mgx_ipred `pc', touse(`touse') spec(`ps`o'') if "`elasticity'" == "eyex" qui replace `nv' = `nv' * `v' / `pc' if "`elasticity'" == "dyex" qui replace `nv' = `nv' * `v' if "`elasticity'" == "eydx" qui replace `nv' = `nv' / `pc' } } else if inlist("`ty'", "d", "n") { if "`ty'" == "d" qui replace `v' = 1 if `touse' else qui replace `v' = `ov`iv'' + 1 if `touse' _mgx_ipred `p1', touse(`touse') spec(`ps`o'') if "`ty'" == "d" qui replace `v' = 0 if `touse' else qui replace `v' = `ov`iv'' if `touse' _mgx_ipred `p0', touse(`touse') spec(`ps`o'') qui replace `v' = `ov`iv'' if `touse' qui gen double `nv' = `p1' - `p0' if `touse' } else if "`ty'" == "s" { local myset "" forvalues s = 1/`nsets' { if `: list v in sdef`s'' local myset `sdef`s'' } foreach e of local myset { qui replace `e' = (`"`e'"' == "`v'") if `touse' } _mgx_ipred `p1', touse(`touse') spec(`ps`o'') foreach e of local myset { qui replace `e' = 0 if `touse' } _mgx_ipred `p0', touse(`touse') spec(`ps`o'') foreach e of local myset { local ie : list posof "`e'" in touched qui replace `e' = `ov`ie'' if `touse' } qui gen double `nv' = `p1' - `p0' if `touse' } else if "`ty'" == "f" { qui levelsof `v' if e(sample), local(levs) local base "" foreach l of local levs { if `: list posof "`l'b.`v'" in cn0' local base `l' } if "`base'" == "" local base : word 1 of `levs' qui replace `v' = `lev' if `touse' _mgx_ipred `p1', touse(`touse') spec(`ps`o'') qui replace `v' = `base' if `touse' _mgx_ipred `p0', touse(`touse') spec(`ps`o'') qui replace `v' = `ov`iv'' if `touse' qui gen double `nv' = `p1' - `p0' if `touse' } qui replace `nv' = `scale' * `nv' label var `nv' "Obs.-level effect of `nm' on `=cond("`eqo'"=="_", "prediction", "`eqo'")'" local made `made' `nv' } } } local rc = _rc local i 0 foreach v of local touched { local ++i qui replace `v' = `ov`i'' qui recast `ty`i'' `v' } if `rc' { capture drop `made' exit `rc' } di di as txt "Observation-level marginal effects (new variables)" di as txt "{hline 15}{c TT}{hline 62}" di as txt _col(16) "{c |}" _col(20) "Mean" _col(30) "SD" _col(38) "p5" _col(45) "p25" /// _col(53) "p50" _col(61) "p75" _col(69) "p95" _col(74) "%>0" di as txt "{hline 15}{c +}{hline 62}" foreach nv of local made { qui summarize `nv' if `touse' `wt', detail local m = r(mean) local sd = r(sd) local q5 = r(p5) local q25 = r(p25) local q50 = r(p50) local q75 = r(p75) local q95 = r(p95) qui count if `touse' & `nv' > 0 & `nv' < . local pos = r(N) qui count if `touse' & `nv' < . local sh = 100 * `pos' / r(N) di as txt %14s abbrev("`nv'", 14) " {c |}" as res %8.0g `m' %8.0g `sd' %8.0g `q5' /// %8.0g `q25' %8.0g `q50' %8.0g `q75' %8.0g `q95' %6.1f `sh' } di as txt "{hline 15}{c BT}{hline 62}" end /* ========================================================================= */ /* display helpers */ /* ========================================================================= */ program define _mgx_header di di as txt "`e(title)'" _col(51) "Number of obs" _col(67) "=" _col(69) as res %10.0fc e(N) local pl `"`e(predlabel)'"' if e(k_out) > 1 { di as txt "Outcomes:" while `"`pl'"' != "" { gettoken one pl : pl, parse("|") if `"`one'"' != "|" & trim(`"`one'"') != "" di as txt " " as res trim(`"`one'"') } } else di as txt "Prediction: " as res `"`pl'"' if `"`e(atspec)'"' != "" di as txt "Evaluated at: " as res `"`e(atspec)'"' if "`e(by)'" != "" di as txt "Effects by groups of: " as res "`e(by)'" if "`e(elasticity)'" != "" di as txt "Continuous covariates: " as res "`e(elasticity)'" as txt " elasticities" if e(percent) == 1 di as txt "Effects multiplied by 100 (percentage points)" local vt "delta method" if "`e(vce)'" == "bootstrap" local vt "bootstrap, `=e(N_reps)' replications" if "`e(vce)'" == "mi" local vt "multiple imputation (M = `=e(M_mi)'), Rubin's rules" di as txt "Engine: " as res "`e(engine)'" as txt " Standard errors: " as res "`vt'" end program define _mgx_footnotes if "`e(continuous)'" != "" di as txt " dy/dx (partial derivative): " as res "`e(continuous)'" if "`e(elastic)'" != "" di as txt " `e(elasticity)' elasticity: " as res "`e(elastic)'" if "`e(dummies)'" != "" di as txt " discrete change of dummy from 0 to 1: " as res "`e(dummies)'" if "`e(dsets)'" != "" { di as txt " discrete change within dummy sets (vs. all-zero reference): " as res "`e(dsets)'" if "`e(dsubpop)'" != "" di as txt " (averaged over own and reference category only)" } if "`e(factors)'" != "" di as txt " factor variables, discrete change from base level: " as res "`e(factors)'" if "`e(counts)'" != "" di as txt " discrete change of count from x to x+1: " as res "`e(counts)'" end program define _mgx_table syntax , b(name) v(name) level(cilevel) title(string asis) local k = colsof(`b') local names : colnames `b' local eqs : coleq `b' local zc = invnormal(1 - (100 - `level') / 200) di di as txt `title' di as txt "{hline 19}{c TT}{hline 58}" di as txt _col(20) "{c |}" _col(24) "Effect" _col(33) "Std. err." _col(47) "z" /// _col(51) "P>|z|" _col(58) "[`level'% conf. interval]" di as txt "{hline 19}{c +}{hline 58}" forvalues i = 1/`k' { local nm : word `i' of `names' local eq : word `i' of `eqs' local lab = cond("`eq'" == "_" | "`eq'" == "", "`nm'", "`eq':`nm'") local lab = abbrev("`lab'", 18) local bb = `b'[1, `i'] local vv = `v'[`i', `i'] if `vv' < 1e-24 | `vv' >= . local vv = 0 local ss = sqrt(`vv') if `ss' > 0 { local zz = `bb' / `ss' local pp = 2 * normal(-abs(`zz')) di as txt %18s "`lab'" _col(20) "{c |}" as res /// _col(21) %9.0g `bb' _col(32) %9.0g `ss' _col(43) %6.2f `zz' /// _col(51) %5.3f `pp' _col(58) %9.0g (`bb' - `zc' * `ss') /// _col(69) %9.0g (`bb' + `zc' * `ss') } else { di as txt %18s "`lab'" _col(20) "{c |}" as res /// _col(21) %9.0g `bb' _col(32) %9.0g 0 } } di as txt "{hline 19}{c BT}{hline 58}" end /* ========================================================================= */ /* export and graph (in a frame when available, otherwise preserve) */ /* ========================================================================= */ program define _mgx_export syntax , b(name) v(name) level(cilevel) [ saving(string) graph gopts(string asis) title(string) ] local done 0 if c(stata_version) >= 16 { tempname fr capture version 16: frame create `fr' if !_rc { capture noisily version 16: frame `fr': _mgx_exbody , b(`b') v(`v') level(`level') /// saving(`saving') `graph' gopts(`gopts') title(`title') local rc = _rc capture version 16: frame drop `fr' if `rc' exit `rc' local done 1 } } if !`done' { preserve drop _all _mgx_exbody , b(`b') v(`v') level(`level') saving(`saving') `graph' gopts(`gopts') title(`title') restore } end program define _mgx_exbody syntax , b(name) v(name) level(cilevel) [ saving(string) graph gopts(string asis) title(string) ] local k = colsof(`b') local names : colnames `b' local eqs : coleq `b' local zc = invnormal(1 - (100 - `level') / 200) quietly { set obs `k' gen str32 outcome = "" gen str80 variable = "" gen double effect = . gen double se = . forvalues i = 1/`k' { replace outcome = "`: word `i' of `eqs''" in `i' replace variable = "`: word `i' of `names''" in `i' replace effect = `b'[1, `i'] in `i' replace se = sqrt(`v'[`i', `i']) in `i' } replace outcome = "" if outcome == "_" gen double z = effect / se gen double p = 2 * normal(-abs(z)) gen double lb = effect - `zc' * se gen double ub = effect + `zc' * se gen long order = _n } if `"`saving'"' != "" { gettoken fn sopt : saving, parse(",") local fn = trim(`"`fn'"') local sopt : subinstr local sopt "," "", all local sopt = trim("`sopt'") local ext = lower(substr(`"`fn'"', -4, .)) if `"`ext'"' == ".csv" { if c(stata_version) >= 13 export delimited using `"`fn'"', `sopt' else outsheet using `"`fn'"', comma `sopt' } else if `"`ext'"' == "xlsx" | `"`ext'"' == ".xls" { export excel using `"`fn'"', firstrow(variables) `sopt' } else if `"`ext'"' == ".dta" { save `"`fn'"', `sopt' } else if `"`ext'"' == ".tex" { tempname fh file open `fh' using `"`fn'"', write text `sopt' file write `fh' "\begin{tabular}{llrrrr}" _n "\hline" _n file write `fh' "Outcome & Variable & Effect & Std. Err. & z & P \\" _n "\hline" _n forvalues i = 1/`k' { local o = outcome[`i'] local vv = variable[`i'] local vv : subinstr local vv "_" "\_", all local o : subinstr local o "_" "\_", all local st "" if p[`i'] < 0.10 local st "^{*}" if p[`i'] < 0.05 local st "^{**}" if p[`i'] < 0.01 local st "^{***}" file write `fh' "`o' & `vv' & $" %9.4f (effect[`i']) "`st'$ & (" %9.4f (se[`i']) ") & " /// %6.2f (z[`i']) " & " %5.3f (p[`i']) " \\" _n } file write `fh' "\hline" _n "\end{tabular}" _n file close `fh' } else { di as err "saving(): file extension must be .csv, .xlsx, .xls, .dta or .tex" exit 198 } di as txt `"(results written to `fn')"' } if "`graph'" != "" { quietly { bysort outcome (order): gen int pos = _n sort order summarize pos, meanonly local np = r(max) capture label drop _mgxlab forvalues i = 1/`np' { local nm = variable[`i'] label define _mgxlab `i' "`nm'", add } label values pos _mgxlab } local byopt "" local tl "" qui count if outcome != "" if r(N) local byopt by(outcome, note("") title(`"`title'"', size(medsmall))) else local tl title(`"`title'"', size(medsmall)) twoway (rcap lb ub pos, horizontal) (scatter pos effect), /// ylabel(1(1)`np', valuelabel angle(0) labsize(small)) /// yscale(reverse) xline(0, lpattern(dash)) legend(off) /// ytitle("") xtitle("Marginal effect (`level'% CI)") `byopt' `tl' `gopts' } end /* ========================================================================= */ /* selftest: certification on Stata's own example data */ /* ========================================================================= */ program define _mgx_selftest, rclass syntax [, TOLerance(real 1e-6) ] local tolI = max(`tolerance', 1e-5) tempname H M R _estimates hold `H', nullok restore preserve global MGXST_PASS 0 global MGXST_FAIL 0 di di as txt "{bf:margeffx selftest} (Stata " c(stata_version) ", margeffx 2.0.1)" di as txt "{hline 62}" /* 1 logit: AME of continuous, factor and dummy covariates; SE */ capture noisily { quietly sysuse nlsw88, clear quietly logit union age grade i.race married c.tenure##c.tenure quietly margeffx matrix `M' = e(mfx_b) matrix `R' = e(mfx_V) quietly margins, dydx(age race) _mgx_stchk "logit AME, continuous" `=el(`M',1,colnumb(`M',"age"))' `=el(r(b),1,colnumb(r(b),"age"))' `tolerance' _mgx_stchk "logit AME, factor level" `=el(`M',1,colnumb(`M',"2.race"))' `=el(r(b),1,colnumb(r(b),"2.race"))' `tolerance' quietly margins, at(married=0) at(married=1) post _mgx_stchk "logit AME, dummy 0->1" `=el(`M',1,colnumb(`M',"married"))' `=_b[2._at]-_b[1._at]' `tolerance' quietly lincom _b[2._at] - _b[1._at] local c = colnumb(`R', "married") _mgx_stchk "logit SE, dummy (delta)" `=sqrt(el(`R',`c',`c'))' `=r(se)' `tolerance' } if _rc _mgx_stfail "logit block" _rc /* 2 probit at means */ capture noisily { quietly sysuse nlsw88, clear quietly probit union age grade married quietly margeffx, at(mean) matrix `M' = e(mfx_b) quietly margins, dydx(age) atmeans _mgx_stchk "probit MEM" `=el(`M',1,colnumb(`M',"age"))' `=el(r(b),1,1)' `tolerance' } if _rc _mgx_stfail "probit block" _rc /* 3 ordered logit, one equation per category; adding-up */ capture noisily { quietly sysuse auto, clear quietly ologit rep78 mpg weight foreign quietly margeffx, sumcheck matrix `M' = e(mfx_b) matrix `R' = e(mfx_bsum) quietly margins, dydx(mpg) predict(outcome(3)) _mgx_stchk "ologit AME, category 3" `=el(`M',1,colnumb(`M',"rep78_3:mpg"))' `=el(r(b),1,1)' `tolerance' _mgx_stchk "ologit adding-up" `=el(`R',1,colnumb(`R',"mpg"))' `=0' 1e-8 } if _rc _mgx_stfail "ologit block" _rc /* 4 multinomial logit */ capture noisily { quietly sysuse nlsw88, clear quietly mlogit race age grade union quietly margeffx matrix `M' = e(mfx_b) quietly margins, dydx(age) predict(outcome(2)) _mgx_stchk "mlogit AME, outcome 2" `=el(`M',1,colnumb(`M',"race_2:age"))' `=el(r(b),1,1)' `tolerance' } if _rc _mgx_stfail "mlogit block" _rc /* 5 Poisson */ capture noisily { quietly sysuse auto, clear quietly poisson rep78 mpg foreign quietly margeffx matrix `M' = e(mfx_b) quietly margins, dydx(mpg) _mgx_stchk "poisson AME" `=el(`M',1,colnumb(`M',"mpg"))' `=el(r(b),1,1)' `tolerance' } if _rc _mgx_stfail "poisson block" _rc /* 6 internal engine against margins */ capture noisily { quietly sysuse nlsw88, clear quietly logit union age grade i.race married quietly margeffx matrix `M' = e(mfx_b) matrix `R' = e(mfx_V) quietly margeffx, engine(internal) tempname M2 R2 matrix `M2' = e(mfx_b) matrix `R2' = e(mfx_V) foreach t in age 2.race married { local c = colnumb(`M', "`t'") _mgx_stchk "internal engine, `t'" `=el(`M2',1,`c')' `=el(`M',1,`c')' `tolerI' _mgx_stchk "internal engine SE, `t'" `=sqrt(el(`R2',`c',`c'))' `=sqrt(el(`R',`c',`c'))' 1e-3 } } if _rc _mgx_stfail "internal-engine block" _rc /* 7 count option: x -> x+1 */ capture noisily { quietly sysuse nlsw88, clear quietly logit union age grade married quietly margeffx, count matrix `M' = e(mfx_b) quietly margins local m0 = el(r(b),1,1) quietly replace grade = grade + 1 if e(sample) quietly margins local m1 = el(r(b),1,1) quietly replace grade = grade - 1 if e(sample) _mgx_stchk "count, unit change" `=el(`M',1,colnumb(`M',"grade"))' `=`m1'-`m0'' `tolerance' } if _rc _mgx_stfail "count block" _rc /* 8 interaction effect, double difference */ capture noisily { quietly sysuse nlsw88, clear quietly logit union i.married##i.collgrad age quietly margeffx, inteff(married collgrad) local ie = el(e(mfx_bi),1,1) quietly margins, at(married=0 collgrad=0) at(married=1 collgrad=0) /// at(married=0 collgrad=1) at(married=1 collgrad=1) _mgx_stchk "inteff, double difference" `=`ie'' `=(el(r(b),1,4)-el(r(b),1,3))-(el(r(b),1,2)-el(r(b),1,1))' `tolerance' } if _rc _mgx_stfail "inteff block" _rc /* 9 by(): subgroup effect */ capture noisily { quietly sysuse nlsw88, clear quietly logit union age grade married south quietly margeffx, by(south) sdiff matrix `M' = e(mfx_b) quietly margins if south == 1, dydx(age) _mgx_stchk "by(), group effect" `=el(`M',1,colnumb(`M',"south_1:age"))' `=el(r(b),1,1)' `tolerance' } if _rc _mgx_stfail "by block" _rc /* 10 generate(): mean of observation-level effects = AME */ capture noisily { quietly sysuse nlsw88, clear quietly logit union age grade married quietly margeffx, generate(stme) matrix `M' = e(mfx_b) quietly summarize stme_age if e(sample) _mgx_stchk "generate(), mean = AME" `=r(mean)' `=el(`M',1,colnumb(`M',"age"))' `tolerI' } if _rc _mgx_stfail "generate block" _rc /* 11 cspmed: margeffx after cspmed equals margeffx after the same logit */ capture which cspmed if !_rc { capture which cspmed_p if _rc { di as err " cspmed_p.ado not found: copy cspmed.ado, cspmed_p.ado and cspmed.sthlp" di as err " (version 1.2.2) into the folder shown by -which cspmed-, then type -discard-" } else { capture noisily { quietly { clear set obs 1500 set seed 271828 gen double x = rnormal() gen byte d = runiform() < .5 gen double m = .5*d + .3*x + rnormal() gen byte y = runiform() < invlogit(-.2 + .4*d + .6*m + .3*x) cspmed y, treatment(d) mediators(m) controls(x) estimator(logit) nodiag margeffx } matrix `M' = e(mfx_b) quietly logit y d m x quietly margeffx tempname M3 matrix `M3' = e(mfx_b) foreach t in d m x { _mgx_stchk "cspmed, `t'" `=el(`M',1,colnumb(`M',"`t'"))' `=el(`M3',1,colnumb(`M3',"`t'"))' 1e-4 } } if _rc _mgx_stfail "cspmed block" _rc } } else di as txt " (cspmed not installed; cspmed test skipped)" di as txt "{hline 62}" local np $MGXST_PASS local nf $MGXST_FAIL if `nf' == 0 di as res "All `np' checks passed." else di as err "`nf' of `=`np'+`nf'' checks FAILED; please report the log." macro drop MGXST_* restore _estimates unhold `H' return scalar N_pass = `np' return scalar N_fail = `nf' end program define _mgx_stchk args name a b tol local va = `a' local vb = `b' local d = reldif(`va', `vb') if `"`tol'"' == "" local tol 1e-6 if `d' <= `tol' & `d' < . { di as txt " pass " as txt %-40s "`name'" as res %12.3e `d' global MGXST_PASS = $MGXST_PASS + 1 } else { di as err " FAIL " %-40s "`name'" %12.3e `d' " (" `va' " vs " `vb' ")" global MGXST_FAIL = $MGXST_FAIL + 1 } end program define _mgx_stfail args name rc di as err " FAIL `name' stopped with error " `rc' global MGXST_FAIL = $MGXST_FAIL + 1 end /* ========================================================================= */ /* Mata: bootstrap variance and percentile CIs; Rubin's rules */ /* ========================================================================= */ version 11 mata: void _mgx_bootv(string scalar bb, string scalar vout, string scalar ciout, real scalar level) { real matrix Q, V, CI real colvector s real scalar a, j, n Q = st_matrix(bb) V = variance(Q) st_matrix(vout, (V + V') / 2) if (ciout == "") return a = (100 - level) / 200 n = rows(Q) CI = J(2, cols(Q), .) for (j = 1; j <= cols(Q); j++) { s = sort(Q[., j], 1) CI[1, j] = s[max((1, ceil(a * n)))] CI[2, j] = s[min((n, ceil((1 - a) * n)))] } st_matrix(ciout, CI) } void _mgx_rubin(string scalar bb, string scalar ws, real scalar M, string scalar bout, string scalar vout, string scalar dfout) { real matrix Q, W, Bv, T real rowvector qbar, r, df Q = st_matrix(bb) qbar = mean(Q) W = st_matrix(ws) / M Bv = (M > 1 ? variance(Q) : J(cols(Q), cols(Q), 0)) T = W + (1 + 1 / M) * Bv r = ((1 + 1 / M) * diagonal(Bv)') :/ diagonal(W)' df = (M - 1) * (1 :+ 1 :/ r):^2 df = editmissing(df, 1e300) st_matrix(bout, qbar) st_matrix(vout, (T + T') / 2) st_matrix(dfout, df) } end