How do I reference a data file with a macro?

北战南征 提交于 2019-12-31 03:15:14

问题


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


来源:https://stackoverflow.com/questions/43081706/how-do-i-reference-a-data-file-with-a-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!