# Re: st: RE: Question about a loop

 From Cameron Hooper <[email protected]> To [email protected] Subject Re: st: RE: Question about a loop Date Tue, 5 Jul 2005 17:57:30 -0400

```Hi

```
```I don't know what

local x 1

is doing here, but it seems irrelevant anyway.
```

A typo. I meant to type: local i 1. This is to initiate `i' for the first iteration of the loop.

```One way to do this is

forval i = 1/10 {
gen op`i' = sum(ret) if inlist(num`i',-1,0,1)
}
```
Thanks. I forgot to add that I do not know how many num* variables I need to loop over. They are created by an earlier <reshape> command. I should have mentioned this in my original post. Your second suggestion does not need to know the number of num* variables and is exactly what I was looking for.

```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)
}
```
```That's the go. Thanks.

Cameron

```
```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/

```
```*
*   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/
```