Hendri Adriaens wrote:
[Maarten Buis wrote:]
-foreach- allows you to loop over a varlist. varlists allow many
shortcuts for specifying a large number of variables. see -help
foreach- and -help varlist-.
If you wanted to store the variable names, you typically would not do
that in a vector but in a local. However, unless you are writing a
general use program, you would typically not need to do that.
I don't think varlist will help me. I need the name of the variable, because
I want to do something with it. That's why I hoped to be able to make string
arrays. Say that I would want to do (in some pseudo code):
v=("a","b","c")
foreach name in v {
gen `name'2=2*`name'
gen `name'3=3*`name'
}
How would I do something like that?
--------------------------------------------------------------------------------
Just like Maarten said.
foreach var of varlist a b c {
forvalues i = 2/3 {
generate `var'`i' = `i' * `var'
}
}
If all you have in your dataset are variables a, b and c, then you can use a
shortcut
foreach var of varlist _all { . . .
If you want to store the list of variable names in a local macro, then you
can
local myvarlist
foreach var of varlist a b c {
local myvarlist `myvarlist' `var'
}
And then you can
foreach element of local myvarlist { . . .
(This last example is similar to the string array or vector that you're
seeking, but you can see that it's not so efficient to do what you want to
do as what Maarten suggested.)
If you have some characteristic that you want to select the variables on
(i.e., you don't know the list of variables in advance), then you can
foreach var of varlist _all {
capture assert [or confirm] <`var' satisfies some set of criteria>
if _rc continue
<do what you want with the variable(s) that meet(s) the criteria>
. . .
}
Joseph Coveney
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/