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

How to concatenate a local variable with a string in Stata

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

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

// Set OS variable for filesystem/directory control: values are: {linux, win}
local os = "linux"

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

if "`os'" == "linux" {
    use "/mnt/DataResearch/DataStageData/CV_PATIENT_LABS.dta"
}
else {
    use "\mrts-400-netapp\DataResearch\DataStageData\CV_PATIENT_LABS.dta"
}

问题在于代码中有很多usesavemerge语句,其中包含硬编码目录,因此将此类控件放入DO 文件不仅乏味,也不是最优雅的解决方案。

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

if os == 'linux':
    dir_out = '/mnt/DataResearch/DataStageData/'
elif os == 'win':
    dir_out = '\mrts-400-netapp\DataResearch\DataStageData\'
else:
    pass

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

use = dir_out + "CV_PATIENT_LABS.dta" 

然而,我一生都没有想出如何在 Stata-ease 中做到这一点。

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

欢迎提出任何建议。

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

. local old "start here"

. local new "`old' and follow there"

. di "`new'"
start here and follow there

或者像这样:

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

. di "`new'"
start here and follow there 

参见here for an introduction to local macros

其实不需要第二个局部宏

这有效

"`old'and follow there" 

这让我可以轻松更改具有本地宏名称的目录的所有实例。比必须定义第二个本地宏更优雅。