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...
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 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
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.