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

Re: st: for commands

From   "Nick Cox" <>
To   <>
Subject   Re: st: for commands
Date   Tue, 4 Nov 2003 22:56:04 -0000

Andrew Eggers

> I am used to using the "for" command to write a command that calls
> members from more than one list in order. For example:

> for any a b c \ num 1/3 \ any g h i: gen XYZ = 0

> would generate three variables named a1g, b2h, and c3i, each filled
> with zeros.

> I am trying to graduate from <for> to <forvalue> and <foreach>, and
> wondered how I can do as above with these newer commands.

I wrote about this on 16 October 2002

and more recently in Stata Journal 3(2):185--202 (2003).

That article was a sequel to the article in Stata Journal
2(2):202--222 (2002), a shortened version of which is available
at the URL kindly cited by Dimitriy Masterov in a previous
posting. (The printed version is much fuller than the internet
version, apart from a partly accidental, partly contrived
triple pun on fortitude (forty-twode) - page 42 - the answer
to the question in Douglas Adams' book.)

Be that as it may, the sequel says much more about Andrew's problem
does the prequel.

In essence, -for- stars at the kind of parallel problem cited
by Andrew, whereas -foreach- stars at nested problems. (This
distinction is expanded in the 16 Oct 2002 posting.)

Apart from the answer you don't want

foreach v in a1g b2h c3i {
	gen `v' = 0

there are various ways to do it, discussed in SJ 3(2): 185--202.

Here is one:

local Y "1 2 3"
local Z "g h i"
local i = 1

foreach x in a b c {
	local y : word `i' of `Y'
	local z : word `i++' of `Z'
	gen `x'`y'`z' = 0

You don't like it? I don't blame you (although it's more
long-winded than it need be). Here's another one.
As so often, we could exploit whatever structure happens
to exist:

local Z "g h i"
local i = 0

foreach x in a b c {
	local z : word `++i' of `Z'
	gen `x'`i'`z' = 0

No, it's not much better. However,

1. -for- is optimised for parallel problems; -foreach-
is optimised for nested problems. Each is better playing
at home, not surprisingly.

2. I have used -foreach- fairly intensively over the last
couple of years, and I'd say that parallel problems like
Andrew's (i.e. selecting one value from each of 3 or more lists)
arise in practice pretty rarely. Your experience may differ.


*   For searches and help try:

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