*! version 1.0.1  12aug2002
program define dfbeta2
	version 7.0
	syntax [varlist(default=none)] [, Double CONStant]

	if "`e(cmd)'" ~= "regress" {
		di as err "This command only works after -regress-."
		exit 301
	}

	if "`double'" == "" {
		local type "float"
	}
	else {
		local type "double"
	}

	tempname b
	mat `b' = get(_b)
	local rhs : colnames `b'

	if "`varlist'"=="" & "`constant'"=="" {
		local varlist `rhs'
		local i = 1
		foreach var of local rhs {
			local pos`i' = `i'
			local i = `i' + 1
		}
	}
	else if "`varlist'"!="" {
		unab varlist : `varlist'
		local i = 1
		foreach var of local rhs {
			local j = 1
			foreach var1 of local rhs {
				if "`var'" == "`var1'" {
					local pos`i' = `j'
				}
				local j = `j'+1
			}
			local i = `i'+1
		}
	}

	local len = cond(_caller()<7, 8, 32) - 2

	local i = 0
	local k = 1
	foreach var of local varlist {
		local new ="DF"+substr("`var'",1,`len')
		capture confirm new var `new'
		while _rc {
			local i=`i'+1
			local new "DF`i'"
			capture confirm new var `new'
		}
		Calc `type' `new' `pos`k''
		*predict float `new', dfbeta(`1')
		di in gr %32s "`new'" ":  DFbeta(`var')"
		local k = `k'+1
	}
	if "`constant'" != "" {
		local pos = colsof(`b')
		local new ="DF_cons"
		capture confirm new var `new'
		local i = 1
		while _rc {
			local i=`i'+1
			local new "DF`i'"
			capture confirm new var `new'
		}
		Calc `type' `new' `pos'
	}
end

program define Calc
	args type var k
	tempname V B
	tempvar res hat si2

	mat `V' = e(V)
	mat `V' = `V'/(e(rmse)^2)
	mat `B' = `V'[`k',1...]
	mat score `type' `var' = `B' if e(sample)
	qui predict double `res' if e(sample), res
	qui predict double `hat' if e(sample), hat
	qui replace `var' = `var'*`res'/(1-`hat')
	qui gen double `si2' = (e(rss) - `res'^2/(1-`hat'))/(e(df_r)-1)
	qui replace `var' = `var'/sqrt(`si2'*`V'[`k',`k'])
end