-1

I am trying to refer to a macro inside a loop in Stata. A simple example below.

local x1 age race gender
local x2 age race gender city

local nums 1 2 
foreach i of local nums{
reg y $x`i'
}

I'd like the loop to go through two calues of i(i = 1,2) and run the two regressions. I am having trouble referring to the macro - any help would be appreciated!

Econ_183
  • 1
  • 1

1 Answers1

0

Your code does not show any global macro. The local macro nums looks legally defined and used but makes the code more complicated for no good reason.

local x1 age race gender
local x2 age race gender city

forval i = 1/2 {
    reg y `x`i'' 
}

may be closer to what you want. See documentation on local macros, e.g. this chapter in the manuals.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
  • Thanks for pointing that out, Nick - sorry for not including that in the original q, I've edited it now. I tried `reg y `x`i'' ` in the loop but the resulting reg output has no xvars (age,race,gender) so I'm assuming it didn't refer to the variables in the macro x1 or x2 here. To rephrase the question, I am struggling with using the vars stored in the macro inside a loop. For instance: ` forval i = 1/2{ { foreach i of local nums{ di $x``i'' }`` I know `di $x`i' ` is incorrect, but how do I get to the vars stored in x1 and x2 inside the loop. Thank you! – Econ_183 Apr 08 '20 at 16:02
  • Thanks for fixing your code on one detail. But your comment seems to make a mistake already explained. If you have no global macros defined, the `$` notation is just wrong. Also you seem to be writing a nested loop. There is one and only one loop in your problem. The code in my answer should run so long as you run it all at once. – Nick Cox Apr 08 '20 at 16:04
  • I assume that your real problem is more complicated and that's fine. But for the record two regressions require two `regress` commands and no more. – Nick Cox Apr 08 '20 at 16:10
  • Thank you! Running the whole thing at once with your code works fine. I have a set of regressions but I'm able to do it just with two regress commands now. – Econ_183 Apr 08 '20 at 16:28