File names in a local macro


Last week I needed to convert a number of Stata data files into text files so that they can be uploaded to Googledocs (why Googledocs is another story).  If my file names have a specific pattern, such as:

data2001.dta
data2002.dta
.
.
.
data2009.dta

-forvalues- would have done the trick.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
forvalues y=1/9{
use “data200y'.dta", clear
outfile using "data
200y’.txt”, dictionary replace
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

My file names, however, look like the file names you get when you type -sysuse dir-:

auto.dta
autornd.dta
bplong.dta
bpwide.dta
cancer.dta

If there were few of them, it would have been alright to place them in a local macro by listing all the file names.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
local datafiles auto autornd bplong bpwide cancer
foreach file of local datafiles{
use <em>file</em>'.<em>dta</em>, clear
<strong>outfile using </strong>"
file.txt“, dictionary replace
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

The latter, however, is not efficient since I have to manually type so many file names so that they can be stored in a macro. Here is where Stata’s extended macro functions (-help extended_fcn-) comes to the rescue. Stata has exactly the right function for what I wanted to do.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
local datafiles : dir . files  “*.dta”
foreach file of local datafiles{
local filenew : subinstr local file “.dta” “.txt”
use file', clear
<strong>outfile using </strong>
filenew‘, dictionary replace
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

local datafiles : dir . files  “*.dta”— makes a list, named datafiles, of all files with the extension .dta in the current directory .

local filenew : subinstr local file “.dta” “.txt”— replaces the file extensions of the file names from .dta to .txt and makes a new list, named filenew, of the new file names.

One Response

  1. -fs- from SSC is a wrapper for this extended macro function.

Leave a Reply