Statalist The Stata Listserver

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

Re: st: RE: new local macro from results of loop

From   n j cox <>
Subject   Re: st: RE: new local macro from results of loop
Date   Wed, 30 May 2007 17:14:24 +0100

The principle is shown by a simpler loop:

forval i = 1/10 {
local a `a' `i'

We assume that -local a- has not been defined upstream of this.

First time round the loop, Stata sees, initially,

local a `a' `i'

and first substitutes macro definitions it already knows. -a-
as just assumed doesn't exist, or equivalently it is replaced
by an empty string. -i- is "1", as far as Stata knows, so after substitution Stata sees

local a 1

This is now an assignment. -local a- is assigned whatever follows
it. So -a- is born as "1".

Second time round the loop, Stata sees, after substitution

local a 1 2

and so forth. So -local a- accumulates the changing values of -i-.

A mantra: substitution of macro definitions precedes evaluation of

The double quotes are optional, for most purposes.

If you had

local "`a' `i'"

local -a- would be borm as " 1"

and if you had

local a "`a'`i' "

it would be born as "1 ", and so on. Mostly, but not always, these
extra spaces disappear in the wash.

Similarly, an equals sign is optional, for this problem and for yours.

There is a tutorial covering this in your context at

Cox, N.J. 2002. How to face lists with fortitude. Stata Journal 2(2):202--222

demonstrates the usefulness of for, foreach, forvalues, and
local macros for interactive (non programming) tasks

Earlier versions of that are accessible at

and it's all in the manual somewhere.


Ronnie Babigumira

Both of your suggestions work (they look the same save for the "" in Maartens solution). That said, I have missed the
obvious so I will ask that you help me with the logic

My part of the loop goes through each element and does my stuff

foreach v of local lvstk {
--my stuff--

How exactly does your part work
local lvstknos "`lvstknos' `v'nbeg `v'nend"
local new `new' `v'nbeg `v'nend

It appears that you are each amending a new local (part of my confusion is that this new local has not been initialised
before). My other problem is that I don't see the part that instructs Stata to incrementally build the new local

Again, your solutions both work . I just want to understand the logic

* For searches and help try:

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