Search code examples
statalocalequalitystata-macros

Find _n of Observation(s) that have a certain value


I want to find the observation numbers that correspond to the observations that have a particular value, say 29. I would then like to save these observation numbers in a macro.

Is there a better way to do so than the following clunky and inefficient forvalues loop?

sysuse auto, clear

local n

forvalues i=1/`=_N' {
    if mpg[`i']==29 local n `n' `i'
}

display "`n'"

Solution

  • gen long obsno = _n 
    levelsof obsno if mpg == 29 
    

    is less typing for you. Why do you want this?