如何使用宏引用数据文件? [英] How do I reference a data file with a macro?

查看:87
本文介绍了如何使用宏引用数据文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有各种Stata数据文件.这些位于不同的文件夹中.我还有一个使用这些文件的 do 文件,一次使用一个.

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.

是否可以使用宏来引用我的 do 文件中的特定数据集?

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

例如:

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.

全局定义(不带 dta 扩展名)为:

The global definition (without the dta extension) is:

global datafile = "C:\filepath\mydata"

这用作:

use "$datafile", clear


我的文件路径中的空格如 C:\ A和B report \ mydata.dta .结果,使用上面的本地定义,我得到以下错误:

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:

无效的文件规范

推荐答案

这实际上是基于对本地宏的理解有误的常见错误在Stata工作中.

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

如果您的本地宏 datafile 等于"C:\ A and B report \ mydata.dta" ,则包含双引号是宏定义过程的一部分,而不是存在于存储的宏中.

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.

要查看此内容

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

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

因此,您的 use 命令应如下所示:

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

这篇关于如何使用宏引用数据文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆