program define _ksmwrk version 2.1 /* Args: 1=Y, 2=X, 3=count, 4=bandwidth, 5=smoothed Y, 6=0 (unwtd mean), 1(unwtd line), 2(wtd mean), 3(wtd line). NOTE: bandwidth is expressed as a fraction of the sample size, not a number of sample values. */ capture drop _W capture drop %_5 capture { /* Using symmetric neighbourhoods. %_k is half-bandwidth. Initialise using points 1,...,k+1. Delta is distance between current Y and furthest neighbour in the interval. _W is tricube weight function within the interval. */ gen _W = 1 gen %_5 = . mac def _wtd = (%_6>1) mac def _mean = (%_6==0 | %_6==2) mac def _k = int((%_4*%_3-0.5)/2) mac def _i 0 while %_i<%_3 { mac def _i = %_i+1 mac def _x0 = %_2[%_i] mac def _imk = max(1, %_i-%_k) mac def _ipk = min(%_i+%_k, %_3) if %_wtd { #delimit ; mac def _delta = 1.0001* max(%_2[%_ipk]-%_x0, %_x0-%_2[%_imk]); replace _W = (1-(abs(%_2-%_x0)/%_delta)^3)^3 in %_imk/%_ipk ; #delimit cr } if %_mean { sum %_1 =_W in %_imk/%_ipk replace %_5 = _result(3) in %_i } else { reg %_1 %_2 =_W in %_imk/%_ipk replace %_5 = _b[_cons]+_b[%_2]*%_x0 in %_i } } drop _W exit } exit _rc end