How to Concatenate a Local Variable with a String in Stata

I have a very large DO file that I need to control for whether the code is run in Linux or Windows.

To do this, I thought I would add this chunk of code at the top of the file:

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

And then whenever I had to select the correct filesystem's directory output I would have:

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

The problem is that there are a LOT of use, save and merge statements in the code with hardcoded directories in them, so that putting this type of control into the DO file would not only be tedious, it would not be the most elegant of solutions.

In python, I would just define a variable dir_out as such:

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

and then throughout the DO file, just concatenate dir_test to the file name like:

use = dir_out + "CV_PATIENT_LABS.dta" 

However, I have not for the life of me figured out how to do that in Stata-ease.

A colleague suggested using the built-in Python interpreter to do this, but I can't see how that would be any better than having a ton of the if-then-else control sequences interspersed throughout the code.

Any suggestions would be most welcome.

2

2 Answers

A local macro in Stata (not called a "local variable") can be concatenated with a string like this:

. local old "start here"

. local new "`old' and follow there"

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

or like this:

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

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

See here for an introduction to local macros.

4

Actually did not need the second local macro.

This worked

"`old'and follow there" 

which allowed me to easily changes all instances of directories with the local macro name. A bit more elegant tthan having to define a second local macro.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest