Hi, does anyone know how to compute mean absolute deviation of the median in stata 17?
-
Login or Register
- Log in with
sysuse auto, clear (1978 automobile data) . egen median = median(mpg), by(foreign) . egen wanted = mean(abs(mpg - median)), by(foreign)
clear all
program define mad, rclass
syntax varname [if] [in] [fweight]
marksample touse
if "`weight'" != "" {
local wgt = "[`weight' `exp']"
}
_pctile price if `touse' `wgt'
tempvar dif
gen double `dif' = abs(price-r(r1))
sum `dif' if `touse' `wgt', meanonly
di as txt "mean absolute deviation from median is: " as result %9.3g r(mean)
return scalar mad = r(mean)
end
sysuse auto, clear
mad price
sysuse auto, clear
qui sum price, detail
local median = r(p50)
gen deviation = abs(price - `median')
qui sum deviation, detail
di "Median absolute deviation of the variable price is " r(p50)
egen mad_price=mad(price)
gen deviationD = price - `median'
gen d_score = deviationD / mad_price
qui sum price, detail
local pmedian = r(p50)
local pmin = r(min)
local pmax = r(max)
scatter price d_score , name(g1) xscale(range(-2 12)) xlabel(-2(1)12, grid glpattern(line))
kdensity price , name(g2) xscale(range(3000 16000)) xlabel(3000(1000)16000, grid glpattern(line)) ///
plotregion(margin(l-5.9 r-6.4 t-0 b-0)) ///
xline(`pmedian', lwidth(.4) lcolor(maroon)) ///
xline(`pmin', lwidth(.4) lcolor(navy)) ///
xline(`pmax', lwidth(.4) lcolor(navy))
graph combine g1 g2 , colfirst c(1)
Comment