1) Is it possible to create a vector of strings in stata? 2) If yes, is it then possible to loop through the elements in this vector, performing commands on each element?
To create a single string in stata I know you do this:
local x = "a string"
But I have about 200 data files I need to loop through, and they are not conveniently named with consecutive suffixes like “_2000” “_2001” “_2002” etc. In fact there is no rhyme or reason to the file names, but I do have a list of them which I could easily cut and paste into a string vector, and then call the elements of this vector one by one, as one might do in MATLAB.
Is there a way to do this in stata?
Sure — You just create a list using a typical local call. If you don’t put quotes around the whole thing your lists can be really long.
Then you just use
foreach.The double quotes (
`" "') are used because one of the filenames has quotes around it because of the space. This is a touch faster than puttingforeach filename in `mylist' {on the first line.If you want to manipulate your list, see
help macrolists.Related questions have been asked >1 time on stackoverflow: