Reputation: 593
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
Upvotes: 2
Views: 867
Reputation: 37208
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'"
}
Upvotes: 1