简体   繁体   English

使用*在Stata循环中指定变量不起作用

[英]Using * to specify variables in Stata loop does not work

Why does this code not work in Stata? 为什么这段代码在Stata中不起作用? The error it gives me is that: 它给我的错误是:

* invalid name

However, when I use 但是,当我使用时

sexd1 sexd2 

instead of 代替

sexd*        

it works fine. 它工作正常。 sexd* works fine as a local when I am typing commands in Stata's command box. 当我在Stata的命令框中输入命令时, sexd*作为本地工作正常。

Here is the code: 这是代码:

local list_of_variables weight midpoint_hhinc
tabulate sex, gen(sexd)
local sexd sexd*

foreach i in `list_of_variables'{
    foreach j in `sexd'{
        generate `i'_`j' = `i' * `j'
    }
}

There is an important difference between foreach ... in and foreach ... of . 有一个重要区别foreach ...... inforeach ... of foreach ... in instructs Stata to take the elements of a list literally, so there is no interpretation. foreach ... in指示塔塔采取列表的元素从字面上看,所以没有解释。

So Stata interprets 所以Stata解释道

 foreach j in `sexd' {
     generate `i'_`j' = `i' * `j'
 }

as

(step 1) (第1步)

 foreach j in sexd* {

(step 2) (第2步)

 generate `i'_sexd* = `i' * sexd*

It will also substitute the current value of the local macro i , but the code fails because the * cannot be part of a variable name. 它也将替换本地宏i的当前值,但代码失败,因为*不能是变量名的一部分。

Conversely, although while your use of foreach ... in is perfectly legal, it can be condensed. 相反,尽管使用foreach ... in是完全合法的,但它可以被浓缩。 I would rewrite your code as 我会把你的代码重写为

 tabulate sex, gen(sexd)
 foreach i in weight midpoint_hhinc {
     foreach j of var sexd* {
         generate `i'_`j' = `i' * `j'
     }
 }

This is partly a matter of style. 这部分是风格问题。 You have only one syntax error, but note that there is no gain in putting names in a local macro when you can refer directly to those names. 您只有一个语法错误,但请注意,当您可以直接引用这些名称时,将名称放在本地宏中没有任何好处。

All that said, this looks like code to generate interaction variables, whereas most Stata modelling commands allow you to refer to interactions on the fly. 总而言之,这看起来像生成交互变量的代码,而大多数Stata建模命令允许您动态引用交互。

There is a fairly detailed tutorial on foreach at http://www.stata-journal.com/sjpdf.html?articlenum=pr0005 有关foreach的相当详细的教程, 请访问http://www.stata-journal.com/sjpdf.html?articlenum=pr0005

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

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