program invpctile, rclass
version 8.2
syntax varname [if] [in], value(real) [nq(integer 100)]
tempvar pcts
* local nq 100
marksample touse
pctile `pcts' = `varlist' if `touse', nq(`nq')
qui replace `pcts' in 1/`nq' = abs(`pcts' - `value')
su `pcts' in 1/`nq', meanonly
qui replace `pcts' in 1/`nq' = cond(`pcts' == r(min),_n,.)
su `pcts' in 1/`nq',meanonly
return scalar pctile = r(mean)*100/`nq'
end
This will now properly handle other than integer percentiles (e.g.
deciles, or fractional percentiles):
. invpctile dowclose if dowclose < 2000, nq(200) value(700)
. return list
scalars:
r(pctile) = 29.5
. invpctile dowclose if dowclose < 2000, nq(10) value(700)