宏本身分为名称和内容两部分,类似于变量名和值。它可以分为两类:
- 局部宏 local macros
只能在给定的do file或一段交互的程序中使用 - 全局宏 global macros
在整个程序中都可以使用
接着介绍全局宏( global macros)
global mname [=exp | :extended_fcn | "[string]" | `"[string]"']
即全局宏后面可以跟
- 表达式
- 扩展函数
- “字符串”
- `"字符串"'(字符串中含双引号时用)
局部宏的调用方式:$global_macro_name
注意:左边是英文输入法下“shift+4”
*示例1
. global a 1
. disp $a
1
.
end of do-file
. global b = $a + 2
. disp $b
3
*对比
. local a 1
. disp `a'
1
.
end of do-file
. local b `a' + 2 //此时局部宏`a'不存在,等价于local b 2
. disp `b'
2
*示例2
. global one1 = 100
. local i = 1
. disp $one1
100
. disp $one`i' //显示全局宏one和局部宏i,但是没有定义全局宏one,因此只显示局部宏
1
. disp ${one`i'} //先运行局部宏,再运行全局宏
100
*示例3
. global a "mycity"
. disp $a //如果赋的值不是数值,则stata查找有无变量的名称为mycity,若有则输出该变量第一个观测值,反之报错提示找不到a变量。
mycity not found
. disp "$a"
mycity
*示例4
clear
set obs 10
global a "mycity"
gen $a = "Hangzhou" //等价于gen mycity = "Hangzhou"
*示例5
clear
set obs 10
global a "mycity"
gen $a = "Hangzhou" //等价于gen mycity = "Hangzhou"
*示例6
clear
set obs 10
global a "mycity"
global i = 1
gen $a$i = "Hangzhou" //等价于gen mycity1 = "Hangzhou"
*示例7
clear
set obs 10
global a1 = "mycity"
global i = 1
gen ${a$i} = "Hangzhou" //等价于gen mycity = "Hangzhou"
*示例8
clear
set obs 10
global b1 "mycity"
global a "b"
global i = 1
gen ${$a$i} = "Hangzhou" //等价于gen mycity = "Hangzhou"
参考资料:
【爬虫俱乐部】精通Stata之数据整理
网友评论