简体   繁体   English

Stata中for循环中的宏

[英]Macros in for loop in Stata

I have local variables x1 , x2, and x3 as follows 我有如下局部变量x1 , x2, and x3

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

Now I define local x as 现在我将local x定义为

local x `x1' `x2' `x3' 

Next, I define for loop as 接下来,我将for循环定义为

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

The problem is that stata is giving me the error (note y is dependent variable) 问题是stata给了我错误(注意y是因变量)

invalid name

Any suggestion in this regard will be highly appreciated. 任何有关这方面的建议都将受到高度赞赏。

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''
}

Assuming these are variables, Richardh's solution would obviously work. 假设这些是变量,Richardh的解决方案显然会起作用。 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'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM