sungmoo 发表于 2012-2-23 08:03 
*稍微调整一下(结果不变。补充:若mat值只出现一次,则原数据无匹配可能;若mat值重复两次以上,则原数据有 ...
借楼上大神的程序,修改了一下,实现k近邻的匹配,若有错误,请大家指正!再次赞叹,大神程序写的真好!!!!
上述程序只能实现1:1匹配(因为u=min(q))
如果先对q排序,在取前k个,个人认为就实现了k近邻的匹配
所以:
use match1.dta, clear
bys year ind daq sp (stkcd): g exp=_n if sp
bys year ind daq: egen s=max(exp)
drop if s==.
expandcl s if !sp,cl(year stkcd) gen(g)
bys year stkcd: replace exp=_n if !sp
bys year ind daq exp: egen r=sum(roa*sp)
g q=abs((roa-r)/r) if !sp
sort year ind exp q
bys year ind exp: gen u=_n if !sp
drop if u>k&!sp //k近邻
egen mat=group(year ind daq exp)
drop exp-u
sort mat sp