I don't know what
local x 1
is doing here, but it seems irrelevant anyway. Your
main point is the mapping from num1-num10 to op1-op10.
One way to do this is
forval i = 1/10 {
gen op`i' = sum(ret) if inlist(num`i',-1,0,1)
}
As far as I can guess, that's also the best way
to do it in your problem.
Another way to do it is
foreach v of var num* {
local V : subinstr local v "num" "op"
gen `V' = sum(ret) if inlist(`v',-1,0,1)
}
An advantage of that is that it will work
nicely for an irregular list, e.g. num1, num3, num7,
num42 for which you want op1, op3, op7, op42.
Nick
[email protected]
Cameron Hooper
> Say I have 10 variables named: num1, num2, ..., num10. I want to loop
> over these variables and create 10 new ones named: op1, op2,
> ..., op10.
> The following works:
>
> local x 1
> foreach var of varlist num* {
> gen op`i' = sum(ret) if inlist(num`i',-1,0,1)
> local i = `i' + 1
> }
>
> I was originally thinking of accessing each of the num* variable's
> name, extracting the last digit and appending this to the
> stub 'op' and
> thus create a new variable. But I don't know to access a variables
> name. Can such a thing be done? Can anyone suggest a better way of
> executing this code?
*
* 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/