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]

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

From   "Nick Cox" <>
To   <>
Subject   st: RE: Find variable with first occurrence of a value in a list of variables
Date   Thu, 22 Jul 2010 20:53:21 +0100

The Doctors Ma*rt?n both commented interestingly but left the question a
bit open. 

A fairly general solution would search for string values too. That could
be programmed, but I'll stick to numeric values. This is rather shorter
than your code. There is no need for a "found" flag. 

local what <whatever> 

gen firstfound = "" 

foreach v of varlist <wheretolook> { 
	replace firstfound = "`v'" if `v' == `what' &

In fact the change for string values is just 

... if `v' == "`what'" 

You could condense that by omitting the middle macro. Like Maarten, I
see no great advantage in terminating the loop early. 


Mike Lacy [13 July 2010 14:34] 

I'm looking for a relatively easy way to find, for each observation, 
which variable in a list has the first occurrence of a particular 
value.  I was looking for a built-in solution, but not finding 
something, came up with a "roll your own" solution that seems less 
than ideal, and so am seeking suggestions

// 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' ==
    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. 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.

*   For searches and help try:

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