Thursday, March 16, 2006

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

"Phil Schumm" <pschumm@uchicago.edu> 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 michael.blasnik@verizon.net

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


Tag:


Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?