用户可以决定是循环代码还是只运行一次?

时间:2018-05-17 20:07:00

标签: stata stata-macros

在我的.do文件中,我使用display _request(macroname)向用户询问有关他们想要运行哪些回归的问题。然后我解释他们的答案(在大多数情况下是yesno)并定义出现在回归代码中的另一个宏。我这样做是因为有很多不同的选项可以运行回归,这使得选择运行哪一个变得容易。

现在我想自动化一个进程,循环遍历所有不同的选项,我认为在开始时添加一个额外的问题会很好。这将询问用户是否也不想打扰回答问题,而是运行64种组合(其输出将保存到各种适当命名的不同Word文档)。

所以我有需要运行的回归代码,但是在询问了五个问题之后需要运行 ,或者循环

我可以将代码保存到宏中,然后规定何时运行代码?

编辑:我最好的解决方案是使用do命令运行单独的.do文件。如果我需要更频繁地执行此操作,是否可以在不运行单独的.do文件的情况下完成此操作?

********************** Regressions ***********************

* If you haven't yet installed estout on your machine, you need to do that.
 ssc install estout

pause Note that the regressions will be put in $DataOUT


capture window stopbox rusure "DO YOU WANT TO RUN EVERY POSSIBLE REGRESSION?" "This might take about 10 minutes."
if _rc == 0 {
    global cheat_yn = "yes"
}
if _rc == 1 {
    global cheat_yn = "no"
}


if "$cheat_yn" != "yes" {

/* Great! You're now at the end of the .do file! I'm going to ask you to type
in answers to some questions, to determine what variables you want to work
with. Just type in your answer in the command field, and press enter. */

* 1. Please enter a dependent variable out of searches, encouraged, employed or participates
display _request(dep)
* 2. Grant X female recipient interaction? Enter yes or no.
display _request(gXf_yn)
* 3. Grant X matric interaction? Enter yes or no.
display _request(gXmat)
* 4. Define grant independent variable to include 3 or 5 grant types? Enter 3 or 5.
display _request(n_3_5)
* 5. Dummy for grant or income? Enter dummy or income. (Note that the sample with dummy includes households with no grant income whereas the sample with the income variable only includes households with a positive grant income.)
display _request(grantd)
* 6. Separate out grant into different types or not? Enter yes or no.
display _request(separate)

do "$DataIN\running_regressions.do"

}


if "$cheat_yn" == "yes" {
pause off
foreach dependent in employed participates encouraged searches {
global dep = "`dependent'"
foreach f in no yes {
global gXf_yn = "`f'"
foreach d in income dummy {
global grantd = "`d'"
foreach s in no yes {
global separate = "`s'"
foreach n in 3 5 {
global n_3_5 = "`n'"
foreach m in yes no {
global gXmat = "`m'"
if ( "`dependent'" != "searches" & "`dependent'" != "encouraged" ) | "`f'" != "yes" | "`d'" != "dummy" | "`s'" != "yes" {
* The previous line removes a few regressions that don't run properly

do "$DataIN\running_regressions.do"

}
}
}
}
}
}
}

}

1 个答案:

答案 0 :(得分:0)

有一个使用宏注释掉脚本行的技巧: (不如编写程序那么优雅……)

if answer = "yes" local star = ""
else local star = "*"

然后在脚本行上首先放置'star':如果'star'为空,则运行该行,但是如果'star'包含星号,则将该行视为注释:

`star' display "hi, there"

仅在“答案”为“是”时运行。

如果您可以构建脚本,以便可以注释掉循环的开始和结束行,并且仍然使循环中的命令起作用,那么这可能会对您有所帮助。