cap pro drop sortedf1 pro def sortedf1 args v qui sum `v' local vN=r(N) tempvar univ diff /*initialize univ and diff, can be any other finite value*/ gen `univ'=`v' gen `diff'=1 sortuniq1 `univ' /* sort v and keep only the unique values*/ qui sum `univ' local uN=r(N) local i=1 while `i'<= `vN'{ /* from this line to the end: generate the sorted data density*/ local j=`i' while `j' >= 1 { if `v'[`i']==`univ'[`j']{ continue, break } else{ local j=`j'-1 } } if `j' == 1{ qui replace `diff'=`univ'[2]-`univ'[1] in `i' } else if `j'==`uN'{ qui replace `diff'=`univ'[`uN']-`univ'[`uN'-1] in `i' } else{ qui replace `diff'=`univ'[`j'+1]-`univ'[`j'-1] in `i' } local i=`i' + 1 } *list `diff' replace `v'=2/(_N*`diff') *list `v' end