Reputation: 177
I need to generate all possible tuples of the integer numbers 1,2,3,4 (with exactly 2 items in each tuple).Then, I need to generate
a set of variables that would correspond to the resulting six tuples. Each variable name should contain a reference to a tuple and the value of each variable should be a string version of a tuple itself, as illustrated below:
+--------+--------+--------+--------+--------+--------+
| var_12 | var_13 | var_14 | var_23 | var_24 | var_34 |
+--------+--------+--------+--------+--------+--------+
| 12 | 13 | 14 | 23 | 24 | 34 |
+--------+--------+--------+--------+--------+--------+
While the tuples are generated by using the tuples
user-written command (for details, see http://ideas.repec.org/c/boc/bocode/s456797.html), I am stumbling with generating new variables and assigning values to them in a loop. The code looks as follows and results in a syntax error which presumably stems from using local tuples macros incorrectly, and I would greatly appreciate if someone could help me solving it.
tuples 1 2 3 4, display min(2) max(2)
forval i = 1/`ntuples' {
gen v`i'=`tuple`i''
rename v`i' var_`tuple`i''
}
Upvotes: 1
Views: 1705
Reputation: 37208
tuples
is a user-written command from SSC. Over at www.statalist.org you would be expected to explain where it comes from, and that's a very good idea here too.
In your case, you want say integers such as 12 to represent a tuple such as "1 2" but the latter looks malformed to Stata when you are creating a numeric variable. Stata certainly won't elide the space(s) even if all characters presented otherwise are numeric. So you need to do that explicitly. At the same name giving a variable one name and then promptly renaming it can be compressed.
forval i = 1/`ntuples' {
local I : subinstr local tuple`i' " " "", all
gen var_`I' = `I'
}
Creating a string variable for the tuple with space included would make part of that unnecessary, but the space is still not allowed in the variable name:
forval i = 1/`ntuples' {
local I : subinstr local tuple`i' " " "_", all
gen var_`I' = "`tuple`i''"
}
If this is the whole of your problem, it would have been quicker to write out 6 generate
statements! If this is a toy problem representative of something larger, watch out that say "1 23" and "12 3" would both be mapped to "123", so eliding the spaces is unambiguous only with single digit integers; hence the appeal of holding strings as such.
I am still curious how holding the same tuple in every observation of a variable is a good idea; perhaps your larger purpose would be better met by using string scalars or the local macros themselves.
Upvotes: 4