stata入门中文讲义

更新时间:2024-07-04 03:48:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

Stata及数据处理

目录

第一章 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10

STATA 基础 .......................................................................................................................... 3 命令格式....................................................................................................................................... 4 缩写、关系式和错误信息 ........................................................................................................... 6 do文件 .......................................................................................................................................... 6 标量和矩阵 ................................................................................................................................... 7 使用Stata命令的结果 ................................................................................................................. 8 宏 ................................................................................................................................................ 10 循环语句..................................................................................................................................... 11 用户写的程序 ............................................................................................................................. 15 参考文献..................................................................................................................................... 15 练习 ......................................................................................................................................... 15

第二章数据管理和画图 ............................................................................................................................. 18 2.1数据类型和格式 ............................................................................................................................... 18 2.2 数据输入........................................................................................................................................... 19 2.3 画图 .................................................................................................................................................. 21 第3章线性回归基础 ................................................................................................................................. 22 3.1

数据和数据描述 ......................................................................................................................... 22

变量描述 ............................................................................................................................. 22 简单统计 ............................................................................................................................. 23 二维表 ................................................................................................................................. 23 加统计信息的一维表 ......................................................................................................... 26 统计检验 ............................................................................................................................. 26 数据画图 ............................................................................................................................. 27

3.1.1 3.1.2 3.1.3 3.1.4 3.1.5 3.1.6 3.2

回归分析..................................................................................................................................... 28

1

3.2.1 3.2.2 3.2.3 3.2.4 3.3 3.4

相关分析 ............................................................................................................................. 28 线性回归 ............................................................................................................................. 29 假设检验 Wald test ............................................................................................................ 30 估计结果呈现 ..................................................................................................................... 30

预测............................................................................................................................................. 34 Stata 资源.................................................................................................................................... 35

第4章数据处理的组织方法 ..................................................................................................................... 36 1、可执行程序的编写与执行 ............................................................................................................... 36 方法1:do文件 ................................................................................................................................. 36 方法2:交互式-program-命令 ......................................................................................................... 36 方法3:在do文件中使用program命令 ......................................................................................... 38 方法4:do文件合并 ......................................................................................................................... 39 方法5:ado 文件 ............................................................................................................................... 40 2、do文件的组织 .................................................................................................................................. 40 3、数据导入........................................................................................................................................... 40 4、_n和_N的用法 ................................................................................................................................ 44

2

第一章 STATA 基础

STATA的使用有两种方式,即菜单驱动和命令驱动。菜单驱动比较适合于初学者,容易入学,而命令驱动更有效率,适合于高级用户。我们主要着眼于经验分析,因而重点介绍命令驱动模式。

图1.1 Stata12.1的基本界面

关于STATA的使用,可以参考Stata手册,特别是[GS] Getting Started with Stata,尤其是第1章A sample session和第2章The Stata User Interface。

有关Stata使用的资料非常多,其中Stata官方的有Stata手册,比如对于初学者,[GS]Getting Started with Stata是有用的起点,最有用的手册可能是[U] User’s Guide。除此之外,还有很多的其他相关手册,相关介绍参见用户手册[U] 1 Read this—it will help。

Stata Journal (SJ) 和 Stata Technical Bulletin (STB) 是Stata的官方期刊,里面介绍一些没有包括在当前Stata 安装里的例子和程序。其中,STB是SJ的前身,自2001年起,STB改为SJ。另外,Stata的网站上有很多有用的信息Stata软件本身也提供很多有用的帮助命令,其中使用最多的可能是help命令,比如当你忘记Stata 命令regress的使用方法时,可以在命令窗口输入help regress,从而调出Stata的viewer窗口,提供regress命令的使用方法。有时,你如果不知道具体的命令,也可以使用help命令获得帮助,比如想了解特征的函数命令,但有忘记了,可以使用help function调出所有的函数。

3

另外,Stata还提供search、findit、hsearch等搜索命令。search会在Stata官方帮助文件、

FAQS、例子、SJ、STB等搜索关键词,但不会搜索网络。net search会在网络(包括SJ/STB)上搜索可安装的程序。findit 会进行更广范围的搜索,包括本机和网络信息,并且关键词不必完整。hsearch会在本机上搜索所有的帮助文件(扩展名为.sthlp或hlp的文件),包括官方命令和用户写的命令。 1.1 命令格式

所有Stata命令基本具有下列模式

[prefix:] command [varlist] [= exp][if][in][weight][using filename][, options] 方括号表示可选项,打字机体是直接输入,斜体需要用户替代,其中

Prefix表示前缀,command是相应的Stata命令,varlist是变量列表,exp是表达式,filename是文件名,options表示适用于该命令的一个或多个可选项。Su pric 比如,简单统计命令summarize的命令格式为 summarize [varlist] [if] [in] [weight] [, options]

下划线表示该命令也可缩写为su。以系统自带数据auto.dta为例,看一下summarize命令的使用。

4

. sysuse auto(1978 Automobile Data). summarize Variable Obs Mean Std. Dev. Min Max make 0 price 74 6165.257 2949.496 3291 15906 mpg 74 21.2973 5.785503 12 41 rep78 69 3.405797 .9899323 1 5 headroom 74 2.993243 .8459948 1.5 5 trunk 74 13.75676 4.277404 5 23 weight 74 3019.459 777.1936 1760 4840 length 74 187.9324 22.26634 142 233 turn 74 39.64865 4.399354 31 51displacement 74 197.2973 91.83722 79 425 gear_ratio 74 3.014865 .4562871 2.19 3.89 foreign 74 .2972973 .4601885 0 1

可以利用help summarize查看它的可选项,比如用detail可选项,还可以把变量的偏度和峰度显示出来。

. summarize price, detail Price Percentiles Smallest 1% 3291 3291 5% 3748 329910% 3895 3667 Obs 7425% 4195 3748 Sum of Wgt. 7450% 5006.5 Mean 6165.257 Largest Std. Dev. 2949.49675% 6342 1346690% 11385 13594 Variance 869952695% 13466 14500 Skewness 1.65343499% 15906 15906 Kurtosis 4.819188

再比如回归命令regress的格式为

regress depvar [indepvars] [if] [in] [weight] [, options] 假设我们用mpg (每加仑汽油可以跑多少英里,测度油耗)对价格price和车重weight回归,如下

5

. reg mpg price weight Source SS df MS Number of obs = 74 F( 2, 71) = 66.85 Model 1595.93249 2 797.966246 Prob > F = 0.0000 Residual 847.526967 71 11.9369995 R-squared = 0.6531 Adj R-squared = 0.6434 Total 2443.45946 73 33.4720474 Root MSE = 3.455 mpg Coef. Std. Err. t P>|t| [95% Conf. Interval] price -.0000935 .0001627 -0.57 0.567 -.000418 .0002309 weight -.0058175 .0006175 -9.42 0.000 -.0070489 -.0045862 _cons 39.43966 1.621563 24.32 0.000 36.20635 42.67296

Weight的系数是-0.0058175,表示如果车重增加1000磅,每加仑汽车将少跑5.8英里。一个更复杂一些的使用如下:

. by foreign: regress mpg price weight if weight < 4000, vce(robust)

有时,我们不想看到输出结果,可以使用前缀quietly,比如

. quietly regress mpg price weight

1.2 缩写、关系式和错误信息

Stata命令可以缩写,比如summarize可以缩写为su,regress可以缩写为reg,在help文件中,Stata命令下划线部分即该命令可以缩写的最短形式。加外,任意符*可以表示任意字母,比如sum t*表示对所有首字母为t的变量进行简单统计。

数学运算符有加(+)、减(-)、乘(*)、除(/)、指数(^)、负(前缀-);关系运算符有大于(>)、小于(<)、等(==)、不等于(!=或~=)。

逻辑运算符有与(&)、或(|)、非(!或~)。

Stata运行出错时,会提供错误代码,比如r(111),用户可以交互式的通过search rc 111命令,获得错误代码的意思或直接在输出窗口中点击r(111)得到相应解释。

1.3 do文件

do文件是将Stata命令列表形式生成的一个文本文件,运行该文件时,Stata即会按照文件命令的排列顺序逐条执行。do文件是Stata软件的一个重要特色,在数据处理和实证分析中特别有用。do的书写可以使用任何文本编辑器进行,也可以使用Stata自带的编辑器书写,可以用命令doedit直接调出Stata自带文本编辑器进行编辑。比如我们写一个简单的do文件,将命令sysuse auto.dta, clear、

summarize mpg, detail 放在同一个do文件中,起名为example.do。则我可以使用命令do example.do 来执行该文件。

6

当do文件比较大,命令比较多时,加入解释和说明是必要的。Stata允许在do文件中加入说明。有三种方式,

第1种,直接以*开头进行的一行的说明。 第2种在命令后面直接加// 第3种用/* */或///加注 比如下面的example.do文件

*This is an example of do files with comments log using auto, replace // generate a log file sysuse auto, /* */ clear

/*Summarize variable mpg */ sum mpg /// ,detail

log close //close the log file

当然,也可以通过改变结尾分隔符的方式来做,比如 *change delimiter from cr to semicolomn and back to cr #delimit ;

*more than one command per line and command spans more than one line; log using auto, replace; sysuse auto, clear; summarize mpg; log close; #delimit cr

为了程序可读性,我们通常用///而不使用改变分隔符的形式。 do文件的运行非常简单,直接在命令窗口输入do filename.do即可。 1.4 标量和矩阵

一个标量可以用来储存数字或字符,比如

7

. scalar a=2*3. scalar b=\. display b a2 times 3 =6

矩阵的使用有两种方式,一种是直接在命令窗口利用matrix前缀,另一种使用mata命令。

. matrix define A=(1,2,3\\4,5,6). matrix list AA[2,3] c1 c2 c3r1 1 2 3r2 4 5 6

. mata mata (type end to exit) : A=(1,2,3\\3,4,5): B=(2,3\\5,6): A'*B 1 2 1 17 21 2 24 30 3 31 39 : end

1.5 使用Stata命令的结果

Stata命令的结果有两类,一类是r类、一类是e类,Stata中分析数据但不估计参数的命令称为r类命令,这类命令的结果会保存在r()中,通过return list命令可以列出该命令产生的所有结果,比如,

8

. summarize mpg Variable Obs Mean Std. Dev. Min Max mpg 74 21.2973 5.785503 12 41. return listscalars: r(N) = 74 r(sum_w) = 74 r(mean) = 21.2972972972973 r(Var) = 33.47204738985561 r(sd) = 5.785503209735141 r(min) = 12 r(max) = 41 r(sum) = 1576

因而,可以利用这些信息计算一些有用的参数,比如我们计算mpg的极差,

. scalar range=r(max)-r(min). di range29

那些估计参数的命令称为e类命令,其结果会保存在e()中,利用ereturn list可以列出所有的结果。比如回归命令,

9

r(max) = 41 r(sum) = 1576. scalar range=r(max)-r(min). di range29. reg mpg price weight Source SS df MS Number of obs = 74 F( 2, 71) = 66.85 Model 1595.93249 2 797.966246 Prob > F = 0.0000 Residual 847.526967 71 11.9369995 R-squared = 0.6531 Adj R-squared = 0.6434 Total 2443.45946 73 33.4720474 Root MSE = 3.455 mpg Coef. Std. Err. t P>|t| [95% Conf. Interval] price -.0000935 .0001627 -0.57 0.567 -.000418 .0002309 weight -.0058175 .0006175 -9.42 0.000 -.0070489 -.0045862 _cons 39.43966 1.621563 24.32 0.000 36.20635 42.67296 . ereturn listscalars: e(N) = 74 e(df_m) = 2 e(df_r) = 71 e(F) = 66.84814256414501 e(r2) = .6531446579233134 e(rmse) = 3.454996314099513 e(mss) = 1595.932492798133 e(rss) = 847.5269666613265 e(r2_a) = .6433740849070687 e(ll) = -195.2169813478502 e(ll_0) = -234.3943376482347 e(rank) = 3macros: e(cmdline) : \ e(title) : \ e(marginsok) : \ e(vce) : \ e(depvar) : \ e(cmd) : \ e(properties) : \ e(predict) : \ e(model) : \ e(estat_cmd) : \matrices: e(b) : 1 x 3 e(V) : 3 x 3functions: e(sample) .

1.6 宏

宏(macro)是利用一个字符串代表另一个字符串。比如,我们可以利用宏xlist来代替”price weight”。这种替代可以使程序更短,增加易读性,并且很容易修改。宏分为全局宏和局部宏。 全局宏用global进行定义,并用$进行引用,比如,

10

. global xlist price weight. reg mpg $xlist, noheader mpg Coef. Std. Err. t P>|t| [95% Conf. Interval] price -.0000935 .0001627 -0.57 0.567 -.000418 .0002309 weight -.0058175 .0006175 -9.42 0.000 -.0070489 -.0045862 _cons 39.43966 1.621563 24.32 0.000 36.20635 42.67296

全局宏可以适用于Stata软件的整个期间。比如修改example.do,调整宏xlist,都会起作用的。 Example.do sysuse auto,clear su mpg price weight reg mpg $xlist reg mpg `xlist’

局部宏用local 进行定义,用`’进行引用(其中左引号通常在~键上,与通常的单引号是不同的)。

. local xlist price weight. reg mpg `xlist', noheader mpg Coef. Std. Err. t P>|t| [95% Conf. Interval] price -.0000935 .0001627 -0.57 0.567 -.000418 .0002309 weight -.0058175 .0006175 -9.42 0.000 -.0070489 -.0045862 _cons 39.43966 1.621563 24.32 0.000 36.20635 42.67296

另一个例子

. local y mpg. local x \. reg `y' `x', noheader mpg Coef. Std. Err. t P>|t| [95% Conf. Interval] price -.0000935 .0001627 -0.57 0.567 -.000418 .0002309 weight -.0058175 .0006175 -9.42 0.000 -.0070489 -.0045862 _cons 39.43966 1.621563 24.32 0.000 36.20635 42.67296

1.7 循环语句

11

Stata的循环语句有三种:foreach、forvalues、while。foreach是根据列表中的每一项进行循环,forvalues是根据连续整数进行循环,while是根据用户的条件是否满足进行循环。 先看两处数据产生命令generate和replace,和随机数产生器runiform()。

. clear. set obs 100obs was 0, now 100. set seed 1234. generate x1=runiform(). generate x2=runiform(). generate x3=runiform(). generate x4=runiform(). generate sum=x1+x2+x3+x4

. summarize sum Variable Obs Mean Std. Dev. Min Max sum 100 1.909211 .5527524 .567311 3.092883

下面,我们分别用三种循环语句实现4个变量的求和。 首先用foreach

*foreach loop with a variable list quietly replace sum = 0

foreach var of varlist x1 x2 x3 x4 { }

summarize sum

. *foreach loop with a variable list. quietly replace sum = 0. foreach var of varlist x1 x2 x3 x4 { 2. quietly replace sum = sum +`var' 3. }. summarize sum Variable Obs Mean Std. Dev. Min Max sum 100 1.909211 .5527524 .5673109 3.092883quietly replace sum = sum +`var'

12

下面用forvales quietly replace sum = 0 forvalues i=1(1)4 { }

summarize sum

. quietly replace sum = 0. forvalues i=1(1)4 { 2. quietly replace sum = sum + x`i' 3. }. summarize sum Variable Obs Mean Std. Dev. Min Max sum 100 1.909211 .5527524 .5673109 3.092883quietly replace sum = sum + x`i'

利用while命令 quietly replace sum = 0 local i=1 while `i'<=4 { }

summarize sum

. quietly replace sum = 0. local i=1. while `i'<=4 { 2. quietly replace sum = sum + x`i' 3. local i = `i' + 1 4. } . summarize sum Variable Obs Mean Std. Dev. Min Max sum 100 1.909211 .5527524 .5673109 3.092883quietly replace sum = sum + x`i' local i = `i' + 1

13

1.8 有用的其他命令

用户手册中提出的每个人需要知道的最常用的42条命令 Getting online help [U] 4 Stata’s help and search facilities

help, hsearch, net search, search, findit

Keeping Stata up to date

ado, net, update [U] 28 Using the Internet to keep up to date adoupdate [R] adoupdate

Operating system interface

pwd, cd[D] cd

Using and saving data from disk

save, saveold[D] save use [D] use

append, merge[U] 22 Combining datasets compress [D] compress

Inputting data into Stata [U] 21 Inputting and importing data

import[D] import edit [D] edit

Basic data reporting

describe[D] describe codebook [D] codebook list[D] list

browse [D] edit count [D] count inspect [D] inspect table [R] table

tabulate [R] tabulate oneway and [R] tabulate twoway

Data manipulation [U] 13 Functions and expressions

generate, replace [D] generate egen [D] egen

rename [D] rename, [D] rename group clear [D] clear

drop, keep[D] drop sort [D] sort

encode, decode [D] encode, destring/tostring recode

order [D] order

by [U] 11.5 by varlist: construct reshape [D] reshape

Keeping track of your work

log [U] 15 Saving and printing output—log files notes [D] notes

Convenience

display [R] display

[R] Base Reference Manual

[D] Data Management Reference Manual

14

[G] Graphics Reference Manual [M] Mata Reference Manual

[MV] Multivariate Statistics Reference Manual [P] Programming Reference Manual

[ST] Survival Analysis and Epidemiological Tables Reference Maunal [SVY] Survey Data Reference Manual [TS] Time-Series Reference Manual

[XT] Longitudinal/Panel-Data Reference Manual

1.8 用户写的程序

比如ivreg2,psmatch2, 可以运用findit ivreg2并安装使用

1.9 参考文献

Baum, Christopher F. An Introduction to Modern Econometrics Using Stata

Cameron, A. C. and P. K. Trivedi, 2009, Microeconometrics Using Stata, Stata Press, Texas.

1.10 练习

1. 运用数据auto.dta,获得价格price的简单统计信息,并利用r()的储存的信息计算价格的变异系数(即标准差除以平均值)。

2. 利用数据auto.dta,做mpg对price, weight的回归,并利用e()中储存的信息计算R2。

3. 利用数据auto.dta,定义一个全局宏变量 varlist,代替变量mpg, price, weight,并获得varlist所代表变量的简单统计信息,利用局部宏重复上述过程。

4. 利用数据auto.dta,利用循环语句foreach产生一个新的变量total,等于headroom和length的加和,并用summarize命令检验均值是否正确。

参考答案: 1.

sysuse auto, clear

15

sum price retu list

g cv=r(sd)/r(mean) di cv

. sysuse auto,clear(1978 Automobile Data). sum price Variable Obs Mean Std. Dev. Min Max price 74 6165.257 2949.496 3291 15906. retu listscalars: r(N) = 74 r(sum_w) = 74 r(mean) = 6165.256756756757 r(Var) = 8699525.974268789 r(sd) = 2949.495884768919 r(min) = 3291 r(max) = 15906 r(sum) = 456229. g cv=r(sd)/r(mean). di cv.47840601

2.

sysuse auto,clear reg mpg price weight g r2 = e(mss)/(e(mss)+e(rss)) di r2

16

. sysuse auto,clear(1978 Automobile Data). . reg mpg price weight, noheader mpg Coef. Std. Err. t P>|t| [95% Conf. Interval] price -.0000935 .0001627 -0.57 0.567 -.000418 .0002309 weight -.0058175 .0006175 -9.42 0.000 -.0070489 -.0045862 _cons 39.43966 1.621563 24.32 0.000 36.20635 42.67296 . . g r2 = e(mss)/(e(mss)+e(rss)). . di r2.65314466

3.

sysuse auto, clear

global varlist mpg price weight sum $varlist

local varlist mpg price weight sum `varlist’

. global varlist mpg price weight. . sum $varlist Variable Obs Mean Std. Dev. Min Max mpg 74 21.2973 5.785503 12 41 price 74 6165.257 2949.496 3291 15906 weight 74 3019.459 777.1936 1760 4840. . local varlist mpg price weight. . sum `varlist' Variable Obs Mean Std. Dev. Min Max mpg 74 21.2973 5.785503 12 41 price 74 6165.257 2949.496 3291 15906 weight 74 3019.459 777.1936 1760 4840

17

4.

cap drop sum qui generate sum=0

foreach var of varlist headroom length { } sum sum

. cap drop sum. . qui generate sum=0. . foreach var of varlist headroom length { 2. . qui replace sum = sum + `var' 3. . }. . sum sum Variable Obs Mean Std. Dev. Min Max sum 74 190.9257 22.71468 145 236.5qui replace sum = sum + `var’

第二章数据管理和画图

2.1数据类型和格式

内部数值型数据有五种模式 存在类型 byte int long float

字节数 1 2 4 4 8

最小 -127

最大 100 32,740 2,147,483,620 1.70141173319х1038 8.9984656743х10307

-32,767

-2,147,483,647

-1.70141173319х1038 -8.9984656743х10307

double

另外,还有字符型数据,与其相关的两条命令是destring,将字符型变量转变为数值型,tostring则将数值型转化为字符型。encode/decode

18

数据显示格式可以利用命令format来进行调整,具体参数有 f g e c

固定形式 一般形式 指数形式 千分位加豆号

.2f 3.5555 3.56

可以利用命令help format了解数据显示格式的更多内容。

2.2 数据输入

use import excel insheet odbc

infile (free format) infix (fixed format) import sasxport haver xmluse

Stata格式数据的输入 use filename [, clear nolabel]

use [varlist] [if] [in] using filename [, clear nolabel] 例:use auto, clear

use if foreign==1 using auto, clear 输入文本文件数据

insheet [varlist] using filename [, options] [no]double override default storage type tab tab-delimited data

19

comma comma-delimited data delimiter(\ clear replace data in memory case preserve variable name's case

[no]names variable names are included on the first line of the file 例:

insheet using [path] gdp.txt, clear ….

ODBC 调入ACCESS文件(工业企业数据)

c:\\Windows\\SysWoW64\\odbcad32

odbc load, table(“QY05”)

20

直接从键盘输入 两种方法:edit和input . input y x

y x 1. 3232 343 2. 43324 45634 3. 32423 45343 4. end

其他输入方式,参考help import

*StatTransfer软件可以进行不同格式数据转换

2.3 画图

1. 散点图

[twoway] scatter varlist [if] [in] [weight] [, options] graph matrix varlist [if] [in] [weight] [, options]

sc mpg weight

sc mpg weight || lfit mpg weight

twoway (lfitci mpg weight,lwidth(medthick))(sc mpg weight)

scatter lwage educ, msize(small) || lfit lwage educ, lwidth(medthick)

graph twoway (scatter lwage educ, msize(small) )( lfit lwage educ, lwidth(medthick)), title(\OLS fitted line\

加置信区间:lfitci, qfit, qfitci, fpfitci

graph save [graphname] filename [, asis replace] 或直接用选项

saving(filename[, asis replace])

21

保存的图可以组合起来graph combine,打开盘中的图用graph use graph save save graph to disk

graph use redisplay graph stored on disk graph display redisplay graph stored in memory graph combine combine multiple graphs 2. 直方图

histogram varname [if] [in] [weight] [, [continuous_opts | discrete_opts] options] 3. 核密度图(Kernel density plot)

kdensity varname [if] [in] [weight] [, options] twoway kdensity varname [if] [in] [weight] [, options]

twoway kdensity lwage ,by(male) //显示在两张独立的图上

twoway (kdensity lwage if male==1)(kdensity lwage if male==0) , legend(label(1 “Male”) label(2 “Female”)//同一图中

2.4 更多资源

参考[U] Users Guide和 [D] Data Management Reference Manual。有用的在线帮助命令包括:1) double, string, format; 2) clear, use, insheet, infile, outsheet; 3) summarize, list, label, tabulate, generate, egen, keep drop, recode, sort, gsort, merge, append, collapse; 4) graph, scatter, histogram, kdensity, twoway, graph matrix。

第3章线性回归基础

3.1 数据和数据描述

比如我们研究收入决定模型,使用2002年的中国城镇居民收入调查数据ind02.dta。首先,将数据调入系统,对变量进行描述。 3.1.1 变量描述 use inc02.dta, clear

22

describe wage lwage male age educ exper expersq ownership industry occupation [,detail]

. describe wage lwage male age educ exper expersq ownership industry occupation storage display valuevariable name type format label variable label wage float %9.0g lwage float %9.0g log wagemale int %9.0g male 1 male 0 femaleage float %9.0g ageeduc float %9.0g years of schoolingexper float %9.0g experienceexpersq float %9.0g ownership int %9.0g ownership ownershipindustry int %9.0g industryoccupation int %9.0g occupation

3.1.2 简单统计

summarize wage lwage male age educ exper expersq ownership industry occupation

. summarize wage lwage male age educ exper expersq ownership industry occupation Variable Obs Mean Std. Dev. Min Max wage 9581 11537.45 7974.335 5 144530 lwage 9581 9.121752 .7590605 1.609438 11.88124 male 10105 .5555666 .4969274 0 1 age 10105 40.32855 8.865457 20 60 educ 10105 11.42415 2.985517 0 23 exper 10031 20.11295 9.568137 0 43 expersq 10031 496.0709 382.8571 0 1849 ownership 9781 1.832737 1.271858 1 4 industry 9754 6.160344 3.38035 1 12 occupation 9754 3.684847 1.47195 1 6

tabulate 可以用来对变量列表 3.1.3 二维表

tabulate male [, nolabel] 23

. tabulate male 1 male 0 female Freq. Percent Cum. female 4,491 44.44 44.44 male 5,614 55.56 100.00 Total 10,105 100.00. tabulate male, nolabel 1 male 0 female Freq. Percent Cum. 0 4,491 44.44 44.44 1 5,614 55.56 100.00 Total 10,105 100.00. tabulate industry male

. tab industry male 1 male 0 female industry female male Total 1 50 73 123 2 1,039 1,475 2,514 3 76 164 240 4 99 230 329 5 227 567 794 6 683 547 1,230 7 790 684 1,474 8 297 215 512 9 434 465 899 10 62 114 176 11 134 136 270 12 433 760 1,193 Total 4,324 5,430 9,754

24

. tabulate male ownership, row column Key frequency row percentage column percentage 1 male 0 ownership female SOE COE FOE POE Total female 2,737 389 90 1,102 4,318 63.39 9.01 2.08 25.52 100.00 41.92 55.97 40.72 47.17 44.15 male 3,792 306 131 1,234 5,463 69.41 5.60 2.40 22.59 100.00 58.08 44.03 59.28 52.83 55.85 Total 6,529 695 221 2,336 9,781 66.75 7.11 2.26 23.88 100.00 100.00 100.00 100.00 100.00 100.00

三维表

table male ownership occupation

. table male own occ occupation and ownership 1 male 0 1 2 3 female SOE COE FOE POE SOE COE FOE POE SOE COE FOE POE female 35 3 2 2 804 62 19 108 926 69 28 151 male 182 13 7 871 42 35 150 1,334 72 29 162 occupation and ownership 1 male 0 4 5 6 female SOE COE FOE POE SOE COE FOE POE SOE COE FOE POE female 310 88 21 539 269 85 11 117 356 71 9 110 male 146 34 14 453 304 49 10 107 909 87 41 289

25

3.1.4 加统计信息的一维表

. table male, contents (N wage mean wage sd wage p50 wage) 1 male 0 female N(wage) mean(wage) sd(wage) med(wage) female 4,219 10222.54 7379.265 8532.41 male 5,362 12572.05 8267.957 11119.54

. table male ownership, contents (N wage mean wage sd wage p50 wage) 1 male 0 ownership female SOE COE FOE POE female 2,699 385 83 903 11674.71 7213.589 12509.7 7317.338 7637.997 4694.328 7911.12 6144.484 10260 6060 11288.07 6000 male 3,769 299 127 1,031 13475 8926.686 16487.83 10147.28 7793.849 5751.082 9700.689 9459.863 12080.04 7472.5 13866 7900

tabulate varlist [,summarize]

. tab male, sum(wage) 1 male 0 Summary of wage female Mean Std. Dev. Freq. female 10222.544 7379.2647 4219 male 12572.054 8267.9574 5362 Total 11537.445 7974.3349 9581

统计表格tabstat

tabstat wage educ exper, statistics( count mean p50 skew kurt) column(statistics) . tabstat wage educ exper, stat(count mean p50 skew kurt) col(stat) variable N mean p50 skewness kurtosis wage 9581 11537.45 9996.24 2.562384 19.6333 educ 10105 11.42415 12 -.2533899 3.779897 exper 10031 20.11295 21 -.1663281 2.212653

3.1.5 统计检验

ttest 可以用来检验变量总体均值是否等于某一常数(H0: ?=?*),或检验两个均值是否相等(H0: ?1=?2)

26

. ttest wage, by(male)Two-sample t test with equal variances Group Obs Mean Std. Err. Std. Dev. [95% Conf. Interval] female 4219 10222.54 113.6078 7379.265 9999.813 10445.28 male 5362 12572.05 112.9106 8267.957 12350.7 12793.4 combined 9581 11537.45 81.46837 7974.335 11377.75 11697.14 diff -2349.509 162.3521 -2667.754 -2031.265 diff = mean(female) - mean(male) t = -14.4717Ho: diff = 0 degrees of freedom = 9579 Ha: diff < 0 Ha: diff != 0 Ha: diff > 0 Pr(T < t) = 0.0000 Pr(|T| > |t|) = 0.0000 Pr(T > t) = 1.0000

3.1.6 数据画图

kdensity 和 twoway kdensity可以用来画变量的分布,比如工资的分布 kdensity wage

twoway kdensity wage, by(male)

kdensity wage.00002.00004.00006.00008femalemale0050000100000150000050000100000150000xGraphs by 1 male 0 female

Twoway (kdensity wage if male)(kdensity wage if !male), legend(label(1 male) label (2 female))

27

kdensity wage.00002.00004.00006.000080050000 malex100000 female150000

3.2

回归分析

3.2.1 相关分析

correlate 相关系数,仅对所有变量同时取值时,不考虑缺失值

pwcorr 相关系数,两两计算相关系数,考虑缺失值,可以加参数obs、sig(显著性)

. cor wage educ exper(obs=9518) wage educ exper wage 1.0000 educ 0.2747 1.0000 exper 0.1867 -0.2218 1.0000

. pwcorr wage educ exper, obs sig wage educ exper wage 1.0000 9581 educ 0.2754 1.0000 0.0000 9581 10105 exper 0.1867 -0.2036 1.0000 0.0000 0.0000 9518 10031 1003128

wage educ exper wage 1.0000 educ 0.2747 1.0000 exper 0.1867 -0.2218 1.0000. pwcorr wage educ exper, obs sig wage educ exper wage 1.0000 9581 educ 0.2754 1.0000 0.0000 9581 10105 exper 0.1867 -0.2036 1.0000 0.0000 0.0000 9518 10031 10031

3.2.2 线性回归

regress depvar [indepvars] [if] [in] [weight] [, options]

regress depvar [indepvars] [if] [in] [weight] [, options] options Description Model noconstant suppress constant term hascons has user-supplied constant tsscons compute total sum of squares with constant; seldom used SE/Robust vce(vcetype) vcetype may be ols, robust, cluster clustvar, bootstrap, jackknife, hc2, or hc3 Reporting level(#) set confidence level; default is level(95) beta report standardized beta coefficients eform(string) report exponentiated coefficients and label as string depname(varname) substitute dependent variable name; programmer's option display_options control column formats, row spacing, line width, and display of omitted variables and base and empty cells noheader suppress table header notable suppress coefficient header plus make table extendable mse1 force mean squared error to 1 coeflegend display legend instead of statistics

29

. reg lwage educ exper, vce(robust)Linear regression Number of obs = 9518 F( 2, 9515) = 780.95 Prob > F = 0.0000 R-squared = 0.1582 Root MSE = .69448 Robust lwage Coef. Std. Err. t P>|t| [95% Conf. Interval] educ .0875659 .0026086 33.57 0.000 .0824525 .0926793 exper .0233035 .0008106 28.75 0.000 .0217146 .0248924 _cons 7.641395 .0400242 190.92 0.000 7.562939 7.719851

ereturn list

help regress postestimation 3.2.3 假设检验 Wald test test educ

联合假设 test educ exper 有约束回归 cnsreg constraint 1 educ=.5

cnsreg lwage educ exper, vce(robust)

3.2.4 估计结果呈现

estimate store 可以将e()中的回归结果保存起来。

estimate table 可以将estimate store的结果以表格的形式呈现出来。 estimate stats 可以将样本容量和似然函数值统计出来。 qui: reg lwage educ exper expersq est store m1 est table m1

qui: reg lwage educ exper expersq male est store m2 est table m1 m2 est stats m1 m2

est table m1 m2, b(%9.4f) se stats(N r2 F ll)

30

. qui: reg lwage educ exper. . est store m1. . est table m1 Variable m1 educ .08756591 exper .0233035 _cons 7.6413948 . . qui: reg lwage educ exper male. . est store m2. . est table m1 m2 Variable m1 m2 educ .08756591 .08600261 exper .0233035 .02173852 male .15604851 _cons 7.6413948 7.6038077 . . est stats m1 m2 Model Obs ll(null) ll(model) df AIC BIC m1 9518 -10853.26 -10033.71 3 20073.41 20094.89 m2 9518 -10853.26 -9976.242 4 19960.48 19989.13 Note: N=Obs used in calculating BIC; see [R] BIC note. . est table m1 m2, b(%9.4f) se stats(N r2 F ll) Variable m1 m2 educ 0.0876 0.0860 0.0025 0.0025 exper 0.0233 0.0217 0.0008 0.0008 male 0.1560 0.0145 _cons 7.6414 7.6038 0.0361 0.0360 N 9518 9518 r2 0.1582 0.1683 F 894.0682 641.7474 ll -1.00e+04 -9.98e+03 legend: b/se

31

一个更好的结果呈现命令:esttab,是用户写的非官方命令,用时需要先安装。 esttab [ namelist ] [ using filename ] [ , options ] qui: reg lwage educ exper, vce(robust)

estadd scalar pvalue=Ftail(e(df_r), e(df_m), e(F)) est store m1

qui: reg lwage educ exper male, vce(robust) estadd scalar pvalue=Ftail(e(df_r), e(df_m), e(F)) est store m2

esttab m1 m2 using result.rtf, replace b(.4f) scalars(F pvalue) mtitles star(* .10 ** .05 *** .01)

. esttab m1 m2 (1) (2) lwage lwage educ 0.0876*** 0.0860*** (35.44) (34.96) exper 0.0233*** 0.0217*** (30.35) (27.98) male 0.156*** (10.75) _cons 7.641*** 7.604*** (211.76) (210.98) N 9518 9518 t statistics in parentheses* p<0.05, ** p<0.01, *** p<0.001

esttab m1 m2, scalar(N r2 F ll) star(* .1 ** .05 *** .01)

32

. esttab m1 m2, scalar(N r2 F ll) star(* .1 ** .05 *** .01) (1) (2) lwage lwage educ 0.0876*** 0.0860*** (35.44) (34.96) exper 0.0233*** 0.0217*** (30.35) (27.98) male 0.156*** (10.75) _cons 7.641*** 7.604*** (211.76) (210.98) N 9518 9518 r2 0.158 0.168 F 894.1 641.7 ll -10033.7 -9976.2 t statistics in parentheses* p<.1, ** p<.05, *** p<.01

estimate drop 将内存中的保存的估计结果清除掉。

estpost tabstat wage lwage age male educ exper, by(ownership)statistics(n mean sd) columns(statistics) listwise eststo sum1

esttab sum1, main(mean) aux(sd) nostar unstack noobs nonote nomtitle nonumber

33

3.3 预测

predict [type] newvar [if] [in] [, single_options] xb 预测值

residual残差,在使用预测命令时,最好加上条件if e(sample)以保证预测时所使用的样本和估计时使用的一样。 比较命令 predict y, xb

predict yhat if e(sample), xb 的不同

. predict y(option xb assumed; fitted values)(74 missing values generated). predict yhat if e(sample)(option xb assumed; fitted values)(587 missing values generated). sum y yhat Variable Obs Mean Std. Dev. Min Max y 10031 9.110567 .3162193 7.603807 10.24171 yhat 9518 9.124406 .3104919 7.603807 10.24171

边际效应(marginal effects)

margins [marginlist] [if] [in] [weight] [, response_options options]

response_options Description Main predict(pred_opt) estimate margins for predict, pred_opt expression(pnl_exp) estimate margins for pnl_exp dydx(varlist) estimate marginal effect of variables in varlist eyex(varlist) estimate elasticities of variables in varlist dyex(varlist) estimate semielasticity -- d(y)/d(lnx) eydx(varlist) estimate semielasticity -- d(lny)/d(x) continuous treat factor-level indicators as continuous

options Description 用于求解边际影响,可以用于求解导数、弹性、半弹性等,特别适用非线性模型边际效应的计 Main算。用于线性回归或非线性回归之后。 grand add the overall margin; default if no marginlist At at(atspec) estimate margins at specified values of covariates atmeans estimate margins at the means of covariates asbalanced treat all factor variables as balanced if/in/over over(varlist) estimate margins at unique values of varlist subpop(subspec) estimate margins for subpopulation Within within(varlist) estimate margins at unique values of the nesting factors in34 varlist SE vce(delta) estimate SEs using delta method; the default vce(unconditional) estimate SEs allowing for sampling of covariates nose do not estimate SEs

. margins, dydx(educ exper male)Average marginal effects Number of obs = 9518Model VCE : OLSExpression : Linear prediction, predict()dy/dx w.r.t. : educ exper male Delta-method dy/dx Std. Err. z P>|z| [95% Conf. Interval] educ .0860026 .0024601 34.96 0.000 .0811808 .0908244 exper .0217385 .000777 27.98 0.000 .0202156 .0232615 male .1560485 .0145154 10.75 0.000 .1275988 .1844982

老版本命令mfx

mfx [compute] [if] [in] [, options] mfx replay [, level(#)] options Description Model predict(predict_option) calculate marginal effects (elasticities) for predict_option varlist(varlist) calculate marginal effects (elasticities) for varlist dydx calculate marginal effects; the default eyex calculate elasticities in the form of d(lny)/d(lnx) dyex calculate elasticities in the form of d(y)/d(lnx) eydx calculate elasticities in the form of d(lny)/d(x) nodiscrete treat dummy (indicator) variables as continuous nose do not calculate standard errors

mfx

mfx, varlist(educ) mfx, eyex

3.4 Stata 资源

关键参考资料:[U] User’s Guide 和 [R] regress, [R] regress postestimation, [R] estimates, [R] predict, [R] test。

用户自写程序estout。

35

第4章数据处理的组织方法

1、可执行程序的编写与执行

方法1:do文件

do文件是一个文本文件,里面包含了相关的Stata命令。执行do文件时,Stata会逐条执行do

文件里面的命令。do文件可以运用各种文字编辑器编辑,可以使用Windows自带的记事本,或Stata自带的文本编辑器(可以用doedit命令调用),最好不要使用Word等加格式的编辑器。比如一个简单的do文件:hello.do,内容如下:

*Begin hello.do display “Hello, world” exit

*End hello.do

在Stata命令输入窗口输入

.do hello

Stata就会运行do文件里面的命令,其中带*的是注释语句,Stata会自动忽略,直接执行

display “Hello, world”,在Stata显示区将结果输出。

方法2:交互式-program-命令

另一种方式是在Stata命令窗口直接交互式的使用program命令定义程序,比如在命令窗口输

入:

.program hello

1. display “Hello, world” 2. end

当我们想运行该程序时,直接在命令窗口输入

.hello

则Stata即可运行刚才输入的程序hello

36

在实际使用中,我们很少直接使用交互式定义程序。另外,如果我们想修改该程序,比如我们

在display “Hello, world”之后再加一条命令display “Hi, back”。你在命令窗口输入 .program hello Hello already defined r(110)

Stata会返回错误,因为Stata会记住程序定义。如果你想重新定义一个程序,必须先利用命令

program drop 把同名程序清除: .program drop hello .

.program hello

1. display “Hello, world” 2. display “Hi, back” 3. end

使用program命令定义程序的另一个问题是program不知道Stata内部命令的名称,如果你定义

的程序名称和Stata内容命令同名,当你运行该程序时,实际将执行Stata的内容命令。比如你定义d程序 .program d

1. display “hello, world” 2. end

当执行上述命令时,实际运行的将是describe命令。

第3个问题是program不检测语法,因而如果定义的program中命令有错误,在运行该程序时将出错。如果program定义的程序命令行很长,可以打开Stata的跟踪功能寻找可能发生的错误。 .set trace on .set trace off

打开跟踪时不要忘记关掉,不然你将发现Stata的输出内容会很多。当修改比较复杂的程序

时,可以利用

.set trace on /*打开跟踪*/ .set more off /*将分屏显示关闭*/

.log using junk, replace /*开始一个名为junk.smcl的日志文件*/

37

.运行程序

.log close /*关闭日志文件*/ .set more on /*将分屏显示打开*/

第4个问题是一个单个program文件包含不能超过3500行命令,并且在Stata/SE要小于

135600个字符。

第5个问题不能编辑修改程序。

方法3:在do文件中使用program命令

在do文件中使用program的好处是随时可以修改你的程序,比如我们建议一个hello.do文件

*BEGIN hello.do program hello end exit

*END hello.do

让我们运行一个该do文件,

.do hello .program hello hello already defined r(110); end of do file

出错了,为什么,因为刚才我们利用充互方式已经定义了一个同名的hello程序,因此要运行

我们的do文件,必须先将内存中的同名程序清除,利用 .program drop hello

.do hello <-我们输入的 .program hello <-Stata输入的 1. display “Hello, world” 2. end

display “Hello, world”

38

.exit end of do-file

我们执行hello.do文件时,才把程序hello调入系统,但Stata并没有执行该程序。这时,我们

在命令窗口直接输入程序名,Stata才会执行程序,如下: .hello Hello, world

我们也可以用run hello.do命令将do文件中的程序调入系统,run和do相同,但run不会将do

文件中的命令行显示出来。

方法4:do文件合并

do文件可以做更多,交互式能做的,都可以放在do文件中,因而,我们可以将program

程序定义,及程序执行全部放在同一个do文件中,比如 *BEGIN hello.do program hello end hello exit

*END hello. Do

用do hello执行该do文件,系统会提示错误,因为我们系统中刚才已经定义了hello程

序,所以要先用program drop hello清除掉, 我们可以直接在do文件中将该条命令加入第1行,但如果系统中没有hello程序,运行清除命令时又会提示出错,我们可以在清除命令前加入

capture,表示capture后面的命令出错时,Stata不会报错,也不会停下来,会直接执行后面的语句,但它会将错误保存下来。修改后的程序如下: *BEGIN hello.do capture program drop hello program hello end hello

39

display \display \

exit

*END hello. Do

方法5:ado 文件

ado文件实际上是以do文件形式写program程序方式的扩展,称为自执行文件,其运行类

似于Stata内部命令。加到文件hello.do *BEGIN hello.do program hello end

*END hello.do

直接将do文件保存为hello.ado,内容不变,即

*BEGIN hello.ado program hello end

*END hello.ado

运行该ado文件时,先用program drop hello清除系统内的hello程序,然后在命令窗口直

接输入 .hello

注意:在修改ado文件后,运行之前要用discard清除原ado文件,从而刷新ado文件,

否则你可能发现修改很多次的ado文件运行结果一直没有改变。

display \display “Hello, world”

2、do文件的组织

3、数据导入

Stata数据格式文件,直接用use 可以打开,如果是利用电子表格文件转化来的文本文件,可以使用insheet using 命令导入。如果数据具有固定格式,需要用infile命令导入。假设我们要处理一个包含家庭信息及个人信息的数据,基本数据信息如下:

40

本文来源:https://www.bwwdw.com/article/wmn.html

Top