Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: looping over parallel lists - is there a alternative to "for"?


From   "Michael Blasnik" <[email protected]>
To   <[email protected]>
Subject   Re: st: looping over parallel lists - is there a alternative to "for"?
Date   Thu, 16 Mar 2006 13:16:27 -0500

"Phil Schumm" <[email protected]> wrote:
<snip>
As we all know, -foreach- cannot be used with multiple items. Nested (macro) lists, however, are possible in Stata by using compound quotes. For example:


loc mylist `" "1 a I" "2 b III" "3 c III" "'
foreach element of loc mylist {
di "`: word 1 of `element'' `:word 2 of `element'' `:word 3 of `element''"
}

will produce exactly the same output as the Python code above.

<snip>
Thus, IMHO, the only problem with the Stata example above is that -foreach- cannot be used with multiple items, which is why we have to use the somewhat awkward construction involving inline expansion of the extended macro function "word # of" in the call to -display-. I have no idea how difficult it would be to extend -foreach- in this way, nor have I thought seriously about the issues involved. As I have just shown, however, such an extension might well eliminate any lingering temptations to continue using the now deprecated -for- command.


-- Phil
Maybe I'm not fully understanding this, but -foreach- can be used with multiple items:

. foreach el in "1 a I" "2 b II" "3 c III" {
2. di "`el'"
3. }
1 a I
2 b II
3 c III

You could also pull apart these multiple item list elements using tokenize within the loop if you want.

Michael Blasnik
[email protected]
*
* 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