Bookmark and Share

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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: loops

From   Nick Cox <>
Subject   Re: st: loops
Date   Wed, 21 Dec 2011 11:31:57 +0000

You have several small misunderstandings at once.

1. Using -while- does not imply by itself that its argument is
automatically incremented within the loop. Thus second time around the
loop the local -i- is still 1 and the name -ABD011- is already taken,
hence the error.

2. There is in essence one loop here, a loop over 30 variables. This
should do it

foreach var of varlist AB01_01-AB01_30 {
   local newvar : subinstr local var "_" "", all
   encode `var', gen(`newvar')

Nothing stops you stepping through two loops simultaneously, as you
were trying to do, but it is not necessary.

3. A more subtle potential problem is that you were going to -encode-
your variables separately. This does not guarantee consistent
encodings unless all the distinct values in all the variables occur in
each distinct variable. -multencode- (SSC) is a solution to this
problem. Defining value labels ahead of the -encode- is another.

4. There is some implied confusion between -encode- and -rename-.
-encode- creates new variables and does nothing to the originals. As
new variables they need new names; this is nothing to do with


On Wed, Dec 21, 2011 at 11:10 AM, Hawal Shamon <> wrote:

> I have problems in finding the correct syntax for a nested loop.
> I
>  have the string variables AB01_01, AB01_02, ..., AB01_30 and like to
> encode and rename them at the same time. Renaming is necessary to get
> rid of the "_" in the variables name. Do the result is supposed to be
> AB0101, AB0102, ..., AB0130.
> I tried it with:
> local i 1
> while `i' <=30 {
> foreach var of varlist AB01_01-AB01_30 {
> encode `var', gen(AB01`i')
> }
> }
> and received the following error message:
> .AB011 already defined
> I understand the problem. However, I have no clue how to avoid this problem.

*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index