how do I loop through file names in stata

2020-03-28 04:56发布

问题:

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?

回答1:

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.

local mylist aaa bbb "cc c" dd ee ff 

Then you just use foreach.

foreach filename of local mylist {
  use `"`filename'"'
}

The double quotes (`" "') are used because one of the filenames has quotes around it because of the space. This is a touch faster than putting foreach 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:

  • In Stata how do you assign a long list of variable names to a local macro?
  • Equivalent function of R's "%in%" for Stata


回答2:

On top of Keith's answer: you can also get the list of files in a directory with

    local myfilelist    : dir . files "*.dta"

or more generally

    local theirfilelist : dir <directory name> files <file mask>

See help extended_fcn.



回答3:

What many people might want the combination of the two as I did. Here it is:

* Create a local containing the list of files. 
local myfilelist : dir "." files "*.dta"

* Or manually create the list by typing in the filenames.
local myfilelist "file1.dta" "file2.dta" "file3.dta"

* Then loop through them as you need.
foreach filename of local myfilelist {
  use "`filename'"
}

I hope that helps. Note that locals/macros are limited by 67,784 characters--watch out for this when you have a really long list of files or really long filenames.



标签: stata