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

Re: st: Using foreach and two local macros

From   Gawrich Stefan <[email protected]>
To   "'[email protected]'" <[email protected]>
Subject   Re: st: Using foreach and two local macros
Date   Thu, 7 Aug 2008 17:46:09 +0200

Looping over parallel lists is indeed a very powerful feature. 
To keep it flexible you'll often use a second extended function (word count)
with the forval command.

local x "1 2"
local y "3 4"
local n : word count `x'
forvalues i = 1/`n' {
local x1 : word `i' of `x'
local y1 : word `i' of `y'
di `x1'+2*`x1'+`y1'

But in my view the syntax has two drawbacks:
1) It needs a lot of lines. So it bloats your do-files expecially when you
use it with more than two locals. 
(I often use it for batch graph creation where variables, selections, titles
and settings can make up to ten locals)
2) You have to create new local names inside the loop, which makes it
confusing and error prone 

So sometimes I find it convenient to use that good old (not longer
documented) "for" command again. 

for num 1 2 \ num 3 4 :  di X+2*X+Y  // Yes, you can do it in one line!


local x "1 2"
local y "3 4"
for num `x' \ num `y' :  di X+2*X+Y

But foreach and forvalues are now state of the art, so I don't want to
advertise "for". 
But I think it could be very helpful to save the user from writing all these
extended function lines and add this  
parallel lists functionality to "foreach". 

Best wishes 
Stefan Gawrich

*   For searches and help try:

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