Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# Re: st: double loops with "forvalues"

 From Nick Cox <[email protected]> To [email protected] Subject Re: st: double loops with "forvalues" Date Sun, 17 Jun 2012 01:31:08 +0100

```This solves one problem but it is not what was asked for. In fact,
there is only one loop needed here.

forv i = 1944/1955 {
local j = `i' + 162
gen fa`i' = f`i' if fr == 1
replace fa`i ' = f`j' if fr==0
}

On Sat, Jun 16, 2012 at 11:32 PM, William Buchanan
<[email protected]> wrote:

> You need to generate your variables outside of the loop and then use the loop to replace their values. Stata is trying to do what you want it to, but you're making it generate a variable that already exists when it tries to run through each loop. Have you tried something like:
>
> forv i=1944/1955{
>        g fa`i'=.
>        forv j=2106/2117{
>        replace fa`i'=f`i' if fr==1
>        replace fa`i'=f`j' if fr==0
>        }
> }
>
> Since you only need variables generated based on each of the values of the first loop statement, you should include the generation command there (or outside of the loop).  In your syntax Stata was attempting to generate the variable for each evaluation of both loops.

On Jun 16, 2012, at 3:11 PM, xueliansharon wrote:

>> I want to do a double looping, the commands are as follows:
>>
>> forvalues i=1944/1955 {
>>       forvalues j=2106/2117 {
>>               gen fa`i'=f`i' if fr==1
>>               replace fa`i'=f`j' if fr==0
>>       }
>> }
>>
>> The purpose is to generate 12 new variables (fa1944, fa1945, fa1946, ...,
>> fa1955) with the following characteristics:
>> fa1944=f1944 if fr==1; fa1944=f2106 if fr==0
>> fa1945=f1945 if fr==1; fa1945=f2107 if fr==0
>> fa1946=f1946 if fr==1; fa1946=f2108 if fr==0
>> ...
>> fa1955=f1955 if fr==1; fa1955=f2117 if fr==0
>>
>> However, whenever I run this program, Stata always returns an error message
>> as "fa1944 already defined". Could you please tell me how I should modify
>> the program?

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```