cap program drop totop
program define totop
* Generate temporary variables
tempvar vartarg varorder
* Create a variable vartarg that is temporary and either string or other which is equal to the second argument of the command.
cap gen `vartarg' = `1' if `1' == "`2'"
cap gen `vartarg' = `1' if `1' == `2'
cap confirm variable `vartarg'
if _rc!=0 di as error "No matches found that fit. Check to make sure type matches criteria"
* This variable preserves the previous order of the data before placing the values on top.
gen `varorder' = _n
* This will sort the targeted values to the top and sort everything else to the previous value
cap gsort -`vartarg' `varorder'
*** Program end
* To test it.
set obs 1000
gen het = rnormal()
gen id = _n
* Now let's say we wanted to save to a local macro the het value of the observation with the id 333.
* One way to do with would be
* However this only works because we know there are exactly 332 observations before 333.
* A more robust way would be:
totop id 333
local het333=het /* or even local het333=het since locals automatically read from the top of the list */
* If the variable of interest is not defined.
totop adf asdf
* Or if the type does not match
totop id asdf
Post a Comment