Sunday, July 1, 2012

Command to send a target observation to top of the observation list

* This program sends an observation value to the top of the observation list

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'

end

*** Program end

* To test it.

clear
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

local het333=het[333]
di `het333'

* 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[1] /* or even local het333=het since locals automatically read from the top of the list */
di `het333'

* If the variable of interest is not defined.
totop adf asdf

* Or if the type does not match
totop id asdf


No comments:

Post a Comment