Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: Loops using local macros


From   "Nick Cox" <n.j.cox@durham.ac.uk>
To   <statalist@hsphsun2.harvard.edu>
Subject   st: RE: Loops using local macros
Date   Tue, 16 Mar 2004 13:43:38 -0000

Unless you are using a Stata version before Stata 7, one
answer is not to use -while- at all. 

It is a lot clearer and simpler to use -foreach-: 

foreach v of var x1y1 x1y2 x2y1 x2y2 { 
	tab `v' 
} 

although in this particular example you can also 
go 

tab1 x1y1 x1y2 x2y1 x2y2

and you could possibly also go 

foreach v of var x?y? { 
	tab `v' 
} 

which would also pick up -x3y1- (and not 
the non-existent -x3y2-). 

In terms of your original example, another 
answer is to use -noisily- and -capture-, 
but as implied I really would recommend that 
you go straight to -foreach- (or upgrade 
to Stata 8). 

-foreach- is discussed in [P]. In addition, 
there was a tutorial on -foreach- in Stata Journal 
2(2): 202-222 (2002). Some earlier versions of that are 
on the web, e.g. 
http://fmwww.bc.edu/RePEc/usug2002/fortitude.pdf

Nick 
n.j.cox@durham.ac.uk 

> -----Original Message-----
> From: owner-statalist@hsphsun2.harvard.edu
> [mailto:owner-statalist@hsphsun2.harvard.edu]On Behalf Of Pradeep
> Kurukulasuriya
> Sent: 16 March 2004 13:29
> To: statalist@hsphsun2.harvard.edu
> Subject: st: Loops using local macros
> 
> 
> Dear STATA users:
> 
> I am relatively new STATA user and have a basic question on 
> loops which
> I hope some of you will be able to answer:
> 
> Suppose I have the following variables:
> 
> x1y1 x1y2 x2y1 x2y2
> 
> If I wanted to loop through these variables one possible 
> solution is the
> following:
> 
> local i=1
>  while `i'<=2 {
>    local j=1
>      while `j'<=2 {
>  
>  {SOME STATA FUNCTION e.g tab x`i'`j'}
> 
>   local j=`j'+1
> }
> local i=`i'+1 
> } 
> 
> This works fine. My problem is what do when there is an additional
> variable, such as x3y1.
> 
> In this cases, I need to add a line or something to tell STATA to stop
> the loop after it processes x3y1 and not to look to do x3y2 which
> doesn't exist. I am a bit stuck here and I was hoping you 
> might be able
> to give me some pointers here. Any solutions come to mind?

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



© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index