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

st: RE: foreach nesting


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: foreach nesting
Date   Tue, 16 Sep 2003 09:56:27 +0100

[email protected]
> 
> Can the -foreach- command be nested?  Stata crashes if I 
> try to put a foreach inside another foreach.
> 
> for example:
> 
> local N "0 5 10";
> local Y "y1 y2 y3";
> foreach n in `N'
>    {foreach y in `Y'
>       {reg `y' X if t>`n' } };

Yes indeed. The errors here lie mainly in the placing of the 
left brace. Stata's not terribly rigid about where things 
should go, but it's picky here. This should work: 

local N "0 5 10"
local Y "y1 y2 y3"
foreach n in `N' { 
	foreach y in `Y' {
		reg `y' X if t>`n' 
	} 
}

Note that if you choose to use ; as a 
delimiter you must abide by that decision. 

Nick 
[email protected] 

P.S. we're now into pure style, but I 
would recommend something more like 

foreach n in 0 5 10 { 
	foreach y in y1 y2 y3 {
		reg `y' X if t > `n' 
	} 
}

In this example, the local macros N and Y add nothing 
but indirection. If you revisit your code, the 
version above will be easier to read and understand, 
I suggest. 

Of course, your real example may differ completely 
in this respect. 

*
*   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–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index