Bookmark and Share

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, is already up and running.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

From   Maarten buis <>
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 
slow your program down.

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

Hope this helps,

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


*   For searches and help try:

© Copyright 1996–2016 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index