Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, statalist.org is already up and running.

Re: st: Find variable with first occurrence of a value in a list of variables

 From Maarten buis To statalist-digest@hsphsun2.harvard.edu, statalist@hsphsun2.harvard.edu Subject Re: st: Find variable with first occurrence of a value in a list of variables Date Tue, 13 Jul 2010 14:23:42 +0000 (GMT)

```--- On Tue, 13/7/10, Mike Lacy wrote:
> // Example data: For each case, find first occurrence of a
> "1" in a list of five variables.
> set obs 10
> forval i = 1/5 {
>    gen byte x`i' = (runiform() > 0.6)
> }
> local value_of_interest 1
> tempvar found
> gen byte `found' = 0
> gen str varname = ""
> foreach v of varlist x1-x5 {
>    replace varname  = "`v'" if ///
> (!`found') & (`v' == `value_of_interest')
>    replace `found' = 1 if (`v' == `value_of_interest')
> }
> //
>
> I'm interested in a simple and efficient approach to the
> general case, i.e., not assuming that the variable list of
> interest is numbered.

-forvalues- as you use it in your example expects a varlist,
which is about as general as you can get, i.e. it does not
depend on the variables being numbered. To see the many ways
in which you can specify a varlist, see -help varlist-.

> Among other things, the looping
> approach here would seem a bit better if there was a way to
> terminate the search for each observation the loop when
> `found' ==1.

The looping over observations happens internally, so my guess
would be that any attempt to do what you suggest will actually

I recently encountered a similar problem and I came up with a
sollution that is very similar to yours, and I was happy to
leave it at that. So, I don't see a way to improve upon your
code.

Hope this helps,
Maarten

--------------------------
Maarten L. Buis
Institut fuer Soziologie
Universitaet Tuebingen
Wilhelmstrasse 36
72074 Tuebingen
Germany

http://www.maartenbuis.nl
--------------------------

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```