Bookmark and Share

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


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

Re: st: St: loop within a loop


From   Nick Cox <[email protected]>
To   "[email protected]" <[email protected]>
Subject   Re: st: St: loop within a loop
Date   Tue, 30 Apr 2013 16:25:48 +0100

First off, let's note that each pair of -generate- and -replace- can
be collapsed to one.

gen white = eth==1
generate black= eth==2
generate hispanic= eth==3
generate asian= eth==4
generate mixed= eth==5

Now it's easier to see structure. You don't really need a loop, as you
could do that in two lines with -tabulate, gen()- and -rename-.

But to answer your question in terms of loops. Here's one way, and
there are others.

tokenize "white black hispanic asian mixed"

forval i = 1/5 {
     gen ``i'' = eth == `i'
}

See also broader discussions within

SJ-3-2  pr0009  . . . . . . . . . . . . . Speaking Stata:  Problems with lists
        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  N. J. Cox
        Q2/03   SJ 3(2):185--202                                 (no commands)
        discusses ways of working through lists held in macros

SJ-2-2  pr0005  . . . . . .  Speaking Stata:  How to face lists with fortitude
        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  N. J. Cox
        Q2/02   SJ 2(2):202--222                                 (no commands)
        demonstrates the usefulness of for, foreach, forvalues, and
        local macros for interactive (non programming) tasks

which are both freely available as .pdfs.

Nick
[email protected]


On 30 April 2013 16:17, Adam Guerrero <[email protected]> wrote:
> Hello,
>
> I am trying to create a loop within a loop for the following block of
> code (loop through variables white, black, hispanic, asian, and mixed
> from values 1 to 5):
>
> replace white=1 if eth==1
> generate black=0
> replace black=1 if eth==2
> generate hispanic=0
> replace hispanic=1 if eth==3
> generate asian=0
> replace asian=1 if eth==4
> generate mixed=0
> replace mixed=1 if eth==5
>
> I know decode would be easier, but please consider responding to help
> me out learning how to loop.
>
> I'm relatively new to Stata, so any suggestions would be very much appreciated.
>
> Thank you in advance,
>
> Adam Guerrero
> *
> *   For searches and help try:
> *   http://www.stata.com/help.cgi?search
> *   http://www.stata.com/support/faqs/resources/statalist-faq/
> *   http://www.ats.ucla.edu/stat/stata/
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


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