0

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'"
shadowspawn
  • 3,039
  • 22
  • 26
bill999
  • 2,147
  • 8
  • 51
  • 103

1 Answers1

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

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

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
  • Thanks. The reason I want to do this is to figure out where one particular observation, call it X, lies in the variable `a` distribution—there are 100 observations total, and I want to see how X's `a` value compares with the other 99 values of `a`. I have a variable `b` that I use to find which observation X. The method I am using to see where X lies in the distribution is to first sort on `a` and second to use `b` to locate the observation of interest (similar to `29` above) so I can find its observation number. Probably a better way to go about this, but that's what I came up with. – bill999 Feb 20 '18 at 23:01
  • 1
    Not quite with you but use a quantile plot? `quantile` or `qplot` (SJ). – Nick Cox Feb 20 '18 at 23:04
  • Yes, similar idea to a quantile plot. I just want to find what percentage of total observations lie to the left of a particular observation, and to save that value to a macro. – bill999 Feb 20 '18 at 23:12
  • 1
    `count if mpg < 29` etc. – Nick Cox Feb 20 '18 at 23:13
  • That would be better, but it's actually one step removed in my case—I don't readily know the value that the particular obs. takes (without manually looking or writing more code). For example, create a new variable, `gen n = mpg==29`. The observation that takes on value `1` is the one I am interested in. Then I could use your answer: `gen long obsno = _n` and `levelsof obsno if n==1`. Admittedly, my original question was confusing with the use of `29` as opposed to something more similar to what I actually have. – bill999 Feb 20 '18 at 23:23
  • I am still fuzzy about what you're doing so feel free to edit your question. Best to leave the original version untouched and flag new stuff with EDIT or some such. (Too many times an answer is made nonsensical because an OP having seen that answer writes in a completely different question. You'll know better!) – Nick Cox Feb 21 '18 at 12:05
  • It's probably not necessary here: Your solution answered my question, and I was able to easily apply it to my problem. – bill999 Feb 21 '18 at 14:10