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

st: RE: a simple macro problem

From   "Nick Cox" <>
To   <>
Subject   st: RE: a simple macro problem
Date   Sun, 29 Jun 2008 15:48:19 +0100

Martin Wang asked 
I have the following macro, but it doesn't work as I expected:
I have gov1, gov2

and I wrote:

local dvar=" gov`j' totalassets"
local j=1

while `j'<3{
	reg sales `dvar'
	local j = `j' + 1

I expect this will run sales= gov1 totalassets and  sales= gov2
totalassets, but only the first one ran twice, no second one. 

As Martin Weiss hinted, the difficulty here is that the local macro j 
has not been defined at the point it is used in defining the local dvar.

Martin Wang persisted in wanting a solution like his original. So Eva
Poen suggested 
Make that

local dvar=" gov\`j' totalassets"

and it ought to work. Note the backslash character right in front of
`j'. In Stata, the backslash is an escape character, and prevents the
immediate substitution of the macro. Compare this:

local j 1
di " this is macro `j' "
di " this is macro \`j' "

Eva's code solves Martin's problem to his satisfaction. 

However, I persist in my advice that using the backslash to delay
evaluation -- although for some bizarre reason currently fashionable on
this list -- falls here into the category of solving an easy problem in
a unnecessarily difficult manner.

The issues have already been ventilated in a thread started by Daniel
Hoechle last week. 

Martin Wang's code I would rewrite in stages. 

First, don't use an equals sign when evaluation is not needed. 

Second, use -forval- not -while-. 

Third, don't define -dvar- until needed. 

forval j = 1/3 { 
	local dvar gov`j' totalassets
	reg sales `dvar'

In fact, -dvar- now looks unnecessary. 

forval j = 1/3 { 
	reg sales gov`j' totalassets

The idea that it is good style to define a macro in advance -- and
indirectly by using the backslash to delay evaluation -- is mysterious
and misconceived. In addition, experience on Statalist is that 

1. People who use this often don't understand exactly they are doing
with the backslash. Thus they get into real difficulties when they try
to vary or extend the trick. This can include Stata programmers who
appear from other evidence to be smart, experienced or both. 

2. This practice just leads to code that is unnecessarily tricky and
indeed lengthy. That makes it too difficult to understand, to check, or
to vary. 


*   For searches and help try:

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