Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macros in for loop in Stata

Tags:

loops

local

stata

I have local variables x1 , x2, and x3 as follows

local x1 2 3 5
local x2 5 9 7
local x3 1 3 4

Now I define local x as

local x `x1' `x2' `x3' 

Next, I define for loop as

 foreach var of varlist `x'{
    reg y `var'}

The problem is that stata is giving me the error (note y is dependent variable)

invalid name

Any suggestion in this regard will be highly appreciated.

like image 253
Metrics Avatar asked Jan 15 '23 02:01

Metrics


2 Answers

I think of macros as "delayed typing". This is the approach I use.

sysuse auto, clear
local x1 weight
local x2 headroom trunk
local x3 length turn

forvalue i = 1/3 {
    regress price `x`i''
}
like image 57
Richard Herron Avatar answered Jan 31 '23 08:01

Richard Herron


Assuming these are variables, Richardh's solution would obviously work. However it requires that you rename all your macros even though that's not necessary.

You can just expanding the macros twice:

local x x1 x2 x3
foreach var of local x {
   reg y ``var''
}

You could also do this, but you'll have problems if your lists of variables are too long:

local x "`x1'" "`x2'" "`x3'" 
foreach var of local x {
  reg y `var'
}
like image 34
Keith Avatar answered Jan 31 '23 07:01

Keith