program define ksm version 2.1 /* Last updated: 4-Jun-91. */ if "%_*"=="" { di in bl "-> ksm yvar xvar [if] [in] [,[Line] [Weight] [noGraph] [GEN(newvar)]" di in bl _skip(10) "[BWidth(#)] [LOgit] [Adjust] [graph_options]]" exit 198 } /* Set up */ mac def _varlist "req ex min(2) max(2)" mac def _if "opt" mac def _in "opt" #delimit ; mac def _options "Line Weight noGraph GEN(string) BWidth(real 0) Adjust LOWess LOgit T1title(string) Symbol(string) Connect(string) *"; #delimit cr parse "%_*" if "%_gen"~="" { confirm new var %_gen } parse "%_varlist", parse(" ") if "%_lowess"!="" { mac def _weight "weight" mac def _line "line" } capture { gen _VARY=%_1 %_if %_in gen _VARX=%_2 %_if %_in replace _VARX=. if _VARY==. count if _VARX~=. mac def _cnt = _result(1) if (%_cnt ==0 | %_cnt==.) { di in red "no observations" exit 2000 } _crcslbl _VARY %_1 _crcslbl _VARX %_2 sort _VARX /* Set up complete. */ mac def _bw = %_bwidth if %_bw <= 0 | %_bw >= 1 { mac def _bw .8 } /* smopt=0 (unwtd mean), 1(unwtd line), 2(wtd mean), 3(wtd line). */ if "%_line" == "line" { mac def _smopt = 1 } else { mac def _smopt = 0 } if "%_weight" == "weight" { mac def _smopt = %_smopt+2 } _ksmwrk _VARY _VARX %_cnt %_bw _smooth %_smopt /* Adjust smooth so that mean of Y-values equals mean of smoothed values. */ if "%_adjust" == "adjust" { sum _smooth mac def _mean = _result(3) sum _VARY replace _smooth = _smooth*_result(3)/%_mean } if "%_logit" == "logit" { mac def _adj = 1/%_cnt mac def _small = 0.0001 replace _smooth = %_adj if _smooth<%_small replace _smooth = 1-%_adj if _smooth>(1-%_small) replace _smooth = log(_smooth/(1-_smooth)) } /* TWICE option removed. if "%_twice"=="twice" { mac def _tw = %_twice if %_tw==0 { mac def _tw = %_bw } rename _smooth _newy _ksmwrk _newy _VARX %_cnt %_tw _smooth %_smopt drop _newy } */ /* Graph (if required) */ if "%_graph" ~= "nograph" { if "%_t1title" ==""{ if "%_lowess"!="" { mac def _t1title "Lowess smoother" } else if "%_line" == "line" { mac def _t1title "Running line smoother" } else { mac def _t1title "Running mean smoother" } mac def _t1title "%_t1title, bandwidth = %_bw" } if "%_logit"=="" { if "%_symbol"=="" { mac def _symbol "di" } if "%_connect"=="" { mac def _connect ".l" } graph _VARY _smooth _VARX, %_options /* */ t1("%_t1title") /* */ s(%_symbol) c(%_connect) } else { if "%_symbol"=="" { mac def _symbol "i" } if "%_connect"=="" { mac def _connect "l" } gr _smooth _VARX, %_options t1("%_t1title") /* */ s(%_symbol) c(%_connect) } } /* Create output variable of smoother (if required) */ if "%_gen"~=""{ rename _smooth %_gen } /* Clean up */ capture drop _smooth drop _VARY _VARX exit } if _rc { mac def _rc=_rc capture drop _VARY capture drop _VARX capture drop _smooth capture drop _newy exit %_rc } end