简体   繁体   中英

Using * to specify variables in Stata loop does not work

Why does this code not work in 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.

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 ... in instructs Stata to take the elements of a list literally, so there is no interpretation.

So Stata interprets

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

as

(step 1)

 foreach j in sexd* {

(step 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.

Conversely, although while your use of foreach ... in is perfectly legal, it can be condensed. 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.

There is a fairly detailed tutorial on foreach at http://www.stata-journal.com/sjpdf.html?articlenum=pr0005

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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