2

I have a dataset like this:

string_var | var1 | var2 | var3
var2       |  8   |   8  |  4
var3       |  7   |   5  |  7        
var2       |  10  |   10 |  5

I need to test whether var1 is equal to either var2 or var3, depending on the string that is contained in string_var. My problem is to convert these strings into variable names to do something like:

gen test=1 if var1==string_var

where, after the ==, I need some kind of conversion function to let Stata read the string e.g. var2 as the following:

gen test=1 if var1==var2 

1 Answer 1

1

With just two possibilities, you can branch on the choice. (With several possibilities, I think you'd need a loop.)

clear 
input str4 string_var  var1  var2  var3
var2         8      8    4
var3         7      5    7        
var2         10     10   5
end 

gen test = cond(string_var == "var2", var1 == var2, var1 == var3) 

list 

     +--------------------------------------+
     | string~r   var1   var2   var3   test |
     |--------------------------------------|
  1. |     var2      8      8      4      1 |
  2. |     var3      7      5      7      1 |
  3. |     var2     10     10      5      1 |
     +--------------------------------------+

EDIT:

Here is a more general solution. (If anyone else thinks of a neater solution, be sure to post.)

gen test = . 

levelsof string_var, local(names) 

quietly foreach name of local names { 
    replace test = var1 == `name' if string_var == "`name'" 
}  
Sign up to request clarification or add additional context in comments.

3 Comments

Yes I do have more then two choices, how would this translate into a loop?
It works perfectly. I must admit I had never seen this replacing a variable directly with a tested condition. Thanks a lot.
I haven't often seen this except in the context of row-wise operations in which people want e.g. the name of whichever variable contains the maximum (itself problematic whenever there are ties).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.