How do I reference a data file with a macro?

2019-02-28 01:47发布

问题:

I have various Stata data files. These are located in different folders. I also have a single do file that uses these files, one at a time.

Is there a way to use a macro to reference a particular dataset in my do file?

For example:

local datafile = "C:\filepath\mydata.dta"

The idea is to use this later in the code as follows:

use `datafile', clear

Defining the macro as a global variable works. But I don't want to make it global, so it doesn't prevent me from running two separate programs at a time.

The global definition (without the dta extension) is:

global datafile = "C:\filepath\mydata"

This is used as:

use "$datafile", clear

EDIT:

My file path has spaces like C:\A and B report\mydata.dta. As a result, with the above local definition I get the following error:

invalid file specification

回答1:

This is actually a common error based on a misunderstanding on how local macros in Stata work.

If your local macro datafile is equal to "C:\A and B report\mydata.dta", then the enclosing double quotes are part of the macro definition process and are not present in the stored macro.

To see this:

local datafile = "C:\A and B report\mydata.dta"

macro list _datafile 
_datafile:      C:\A and B report\mydata.dta

Consequently, your use command should instead look as follows:

use "`datafile'", clear

Note that unlike the spaces, which are important, the equal sign (=) is in fact redundant:

local datafile C:\A and B report\mydata.dta

display "`datafile'"
C:\A and B report\mydata.dta