-1

main.do is:

foreach mode in mode1 mode2 {

do run.do

}

and run.do is:

foreach y in y1 y2{ 
reg `y' x
outreg2 using `y'.xls, append ctitle(`mode')

}

It has outreg2, so it produced a txt output. But I found that the column title is empty meaning that Stata couldn't get mode.

That implies that the mode loop in main.do was not inherited by run.do.

How can I make it inherited? It would be wonderful if I could choose whether to make it inherited.

What I tried is:

foreach mode in mode1 mode2 {
global mode `mode'
do run.do
}

and:

foreach mode in mode1 mode2 {
local mode `mode'
do run.do
}

and:

foreach mode in mode1 mode2 {
global mode "`mode'"
do run.do
}

But nothing works.

user42459
  • 883
  • 3
  • 12
  • 29
  • Local and global macros are not considered to be variables in Stata. Naturally, they correspond loosely to entities called variables elsewhere, but Stata use is strict and statistical: a variable in Stata is (and is only) a column in a dataset. See e.g. https://www.stata.com/statalist/archive/2008-08/msg01258.html for more discussion. – Nick Cox Feb 23 '18 at 08:16

2 Answers2

1

Local macros are .... local. meaning visible only within the same interactive session, program, do-file, or (chunk of) code in a do-file editor window.

Globals are a crude solution to making stuff visible everywhere, but you must refer to them as such using $. So in your run.do you would need

ctitle($mode)

Passing the contents as arguments is a much better solution.

See also the help for include.

All this is utterly basic Stata programming. To become competent as a Stata programmer, a minimal reference is https://www.stata.com/manuals/u18.pdf, which is also bundled with Stata on your system (unless your version is several years out of date).

Nick Cox
  • 35,529
  • 6
  • 31
  • 47
1

The following code snippets demonstrate @Nick's excellent advice in the context of your example.

1. Change run.do to call a global instead of a local macro:

foreach mode in mode1 mode2 {
    global mode `mode'
    do run.do
}

foreach y in y1 y2 { 
    reg `y' x
    outreg2 using `y'.xls, append ctitle($mode)
}

macro drop mode

2. Convert run.do into a program and pass local macro mode as argument:

program define foo
foreach y in y1 y2{ 
    reg `y' x
    outreg2 using `y'.xls, append ctitle(`1')
}
end

foreach mode in mode1 mode2 {
    foo `mode'
}

3. include the file run.do in main.do as is:

foreach mode in mode1 mode2 {
    include run.do
}

The last approach is closer to the 'inheritance' solution you are looking for.