Using * to specify variables in Stata loop does not work -
why code not work in stata? error gives me that:
* invalid name
however, when utilize
sexd1 sexd2
instead of
sexd*
it works fine. sexd*
works fine local when typing commands in stata's command box.
here code:
local list_of_variables weight midpoint_hhinc tabulate sex, gen(sexd) local sexd sexd* foreach in `list_of_variables'{ foreach j in `sexd'{ generate `i'_`j' = `i' * `j' } }
there of import difference between foreach
... in
, foreach
... of
. foreach
... in
instructs stata take elements of list literally, there 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 substitute current value of local macro i
, code fails because *
cannot part of variable name.
conversely, although while utilize of foreach
... in
legal, can condensed. rewrite code as
tabulate sex, gen(sexd) foreach in weight midpoint_hhinc { foreach j of var sexd* { generate `i'_`j' = `i' * `j' } }
this partly matter of style. have 1 syntax error, note there no gain in putting names in local macro when can refer straight names.
all said, looks code generate interaction variables, whereas stata modelling commands allow refer interactions on fly.
there detailed tutorial on foreach
@ http://www.stata-journal.com/sjpdf.html?articlenum=pr0005
loops stata
No comments:
Post a Comment