如何在 Stata 中连接局部变量和字符串

hor*_*uzz 3 python stata

我有一个非常大的 DO 文件,我需要控制代码是在 Linux 还是 Windows 中运行。

为此,我想在文件顶部添加这段代码:

// Set OS variable for filesystem/directory control: values are: {linux, win}
local os = "linux"
Run Code Online (Sandbox Code Playgroud)

然后每当我必须选择正确的文件系统的目录输出时,我都会:

if "`os'" == "linux" {
    use "/mnt/DataResearch/DataStageData/CV_PATIENT_LABS.dta"
}
else {
    use "\\mrts-400-netapp\DataResearch\DataStageData\CV_PATIENT_LABS.dta"
}
Run Code Online (Sandbox Code Playgroud)

问题是代码中有很多use,savemerge语句,其中包含硬编码的目录,因此将这种类型的控件放入 DO 文件不仅会很乏味,而且也不是最优雅的解决方案。

在 python 中,我会dir_out这样定义一个变量:

if os == 'linux':
    dir_out = '/mnt/DataResearch/DataStageData/'
elif os == 'win':
    dir_out = '\\mrts-400-netapp\DataResearch\DataStageData\'
else:
    pass
Run Code Online (Sandbox Code Playgroud)

然后在整个 DO 文件中,只需将 dir_test 连接到文件名,例如:

use = dir_out + "CV_PATIENT_LABS.dta" 
Run Code Online (Sandbox Code Playgroud)

然而,我一直没有弄清楚如何在 Stata-ease 中做到这一点。

一位同事建议使用内置的 Python 解释器来执行此操作,但我看不出这比if-then-else在代码中散布大量控制序列更好。

任何建议都将受到欢迎。

Nic*_*Cox 6

Stata 中的局部宏(不称为“局部变量”)可以与如下字符串连接:

. local old "start here"

. local new "`old' and follow there"

. di "`new'"
start here and follow there
Run Code Online (Sandbox Code Playgroud)

或者像这样:

. local new = "`old'" + " and follow there"

. di "`new'"
start here and follow there 
Run Code Online (Sandbox Code Playgroud)

有关本地宏的介绍,请参见此处。

  • 如果非 python 首先出现,那么期望非 python 表现得像 python 是徒劳的,除非某些语法的灵感是相同的。我不明白这里有什么不优雅的。您可以使用并置或使用“+”来连接,后者似乎是您所要求的。 (2认同)