[email protected] commented on various solutions with -for*-:
> The above solutions reminded me that -for-'s functionality
> hasn't quite been
> subsumed by the introduction of -foreach- and -forvalues-
> as I have been
> prone to believe. In version 6, I was quite content using
> the set of
> looping commands (tokenize, while, etc.) and hadn't got to
> learning -for-
> just yet. Thus, when -foreach- and -forvalues- came about
> with Stata 7, I
> saw no reason to bother with it. But the solutions are excellent
> illustrations that -for-'s sometimes results in more
> succinct and, arguably,
> elegant solutions as it avoids unnecessary looping.
>
> To right the wrong, I looked up for.hlp once more and noted small
> inconsistency the examples provided. The last example reads:
>
> (begin excerpt)
> . for any male female: save c:\data\X if sex=="X"
>
> will not work. for will think there are three commands:
>
> save c:
> data
> X if sex=="X"
>
> Instead, you must type
>
> . for any male female: save "c:\data\X" if sex=="X"
> (end of excerpt)
>
> The last line won't work either since the syntax of save
> doesn't allow the
> [if exp] condition -- a non-feature that I, among others,
> wouldn't mind
> seeing implemented in -save- BTW. ;) (NB: I know it's been
> discussed on the
> list before)
>
I agree that the -for- solution is neater here for the problem posed.
However, much of the engineering work behind -for- was done precisely
to achieve this result.
That is, -for- is optimised for what I think of as "parallel"
problems:
do something with the ith member of this list
[ and the ith member of that list
[ and the ith member of THAT list
...
]
]
for i = 1, ..., I
so that there are I results.
In contrast, -foreach- and -forvalues- grow very well indeed with
"nested" problems:
do something with the ith member of this list
[ and the jth member of that list
[ and the kth member of that list
...
]
]
for i = 1, ..., I
j = 1, ..., J
k = 1, ..., K
...
so that there are I * J * K * ... results.
On the whole, I think nested problems are more common in
(my) Stata practice.
On the face of it, it is difficult to devise a simple syntax
to cope with both kinds of problems. Some would argue that
it is difficult to devise a simple syntax to cope with parallel
problems.
Having said that, note that Kit Baum provided an
approach using -foreach- to the original problem.
Nick
[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/