Anda di halaman 1dari 189

STATA

STATA


chrisccb@126.com

STATA

STATA ........................................................................................................................1
..................................................................................................................................................2
1 STATA.....................................................................................................................................6
1.1 .....................................................................................................................................6
1.2 .........................................................................................................................6
1.3 .................................................................................................................8
1.4 .........................................................................................................9
1.5 ...........................................................................................................................10
1.6 ...................................................................................................................11
1.7 .......................................................................................................................12
1.8 ...................................................................................................................................13
2 .....................................................................................................................................15
2.1 .......................................................................................................15
2.2 command...................................................................................................................15
2.3 varlist.........................................................................................................................15
2.4 by varlist...........................................................................................................16
2.5 =exp..............................................................................................................16
2.6 if exp ............................................................................................................17
2.7 in range.............................................................................................................17
2.8 weight.......................................................................................................................17
2.9 ,options.........................................................................................................18
2.10 ....................................................................................................................19
3 .............................................................................................................................................20
3.1 use ....................................................................................20
3.2 ...........................................................................................................................21
3.3 ...................................................................................................................24
3.4 :format .......................................................................................................26
3.5 STATAinput..................................................................................27
3.6 insheet ...........................................................................................30
3.7 :label..................................................................................................................32
3.8 ......................................................................................................................35
4 ....................................................................................................................................36
4.1 ...............................................................................36
4.2 :......................................................................................................36
4.3 .......................................................................................................39
4.4 ...........................................................................................................................39
4.5 :..................................................................................................................41
4.6 .......................................................................................................................42
5 .............................................................................................................................44
5.1 exp.........................................................................................................................44
5.2 function .............................................................................................................46
5.3 math functions...................................................................................................47

chrisccb@126.com

STATA

5.4 string functions..................................................................................................50


5.5 by......................................................................................................................51
6 ............................................................................................................................................54
6.1 ......................................................................................................54
6.2 STATA ...........................................................................54
6.3 Macros: local/global.................................................................................................57
6.4 ..................................................................................................................59
6.5 scalar .........................................................................................................................60
6.6 :tempvartempfile ...............................................................61
6.7 ....................................................................62
7 ....................................................................................................................................67
7.1 :while.................................................................................................................67
7.3 :forvalues...........................................................................................................68
7.3 :foreach..............................................................................................................69
7.4 ...........................................................................................................................71
7.5 ...........................................................................................................................72
7.6 .......................................................................................................................74
8 ............................................................................................................................................75
8.1 ...........................................................................................................................75
8.2 ...................................................................................................................76
8.3 ...........................................................................................................................78
8.4 ...............................................................................81
9 .............................................................................................................................................84
9.1 ...........................................................................................................................84
9.2 ...................................................................................................................89
9.3 by(varname) ..............................................................................................96
9.4 ...........................................................................................................98
9.5 ...................................................................................................................................99
10 .................................................................................................................................100
10.1 .......................................................................................................................100
10.2 .......................................................................................................................101
10.3 .......................................................................................................................103
10.4 ...................................................................................................................105
10.5 .......................................................................................................................107
10.6 ...............................................................................................................................108
10.7 ...............................................................................................................................109
11 ................................................................................................................................115
11.1 .......................................................................................................................115
11.2 .......................................................................................................115
11.3 ...........................................................................................116
11.4 ...............................................................................................117
11.5 .......................................................................................................118
11.6 ...........................................................................................................................119
11.7 .......................................................................................................................120

chrisccb@126.com

STATA

11.8 t..............................................................................................................122
11.9 F ............................................................................................................................122
12 .................................................................................................................................125
12.1 .......................................................................................................................125
12.2 .......................................................126
12.3 ...........................................126
12.4 ...........................................................................128
12.5 F ....................................................................................................................129
12.6 t..........................................................................130
12.7 ...............................................................................................................131
13 ............................................................................................................133
13.1 ...................................................................................................133
13.2 .......................................................................133
13.3 OLS ...............................................................................................134
13.4 MM............................................................................................................135
13.5 ...............................................................................................................135
13.6 ...............................................................................................................136
14 ........................................................................................................................138
14.1 ...............................................................................................................138
14.2 .......................................................................................................................142
14.3 ...............................................................................143
14.3 ...........................................................................................145
15 .............................................................................................................................147
15.1 ...............................................................................................................147
15.2 ...............................................................................................................148
15.3 ..................................................................................................150
15.4 () ...............................................................................................151
15.5 WLSGLS..............................................................................................154
15.6 FGLS ........................................................................................155
Equation Chapter 1 Section 116 ..........................................................................157
16.1 ...............................................................................................................157
16.2 ..........................................................................................158
16.3 AR ............................................................................160
16.4 MA ...............................................................................................163
16.5 ..........................................................................................................167
16.6 ...................................................................................................................168
16.7 ......................................................................................................................170
17 .....................................................................................................172
17.1
17.2
17.3
17.4
17.5
17.6

OLS ..............................................................172
OLS...................................173
OLS ......................................173
......................................................................................................175
......................................................................................................176
......................................................................................................177

chrisccb@126.com

STATA

17.7 ......................................................................................................177
17.8 ..........................................................................................177
18 .............................................................................................................179
18.1 ..............................................................................................................179
18.2 ..............................................................................................................181
18.3 ..........................................................................................................182
18.4 ......................................................................................................184
18.5 ..........................................................................................................187
.......................................................................................................................................189


chrisccb@126.com

STATA

1 STATA
Stata SASSPSS

Stata

Stata

Stata
ADO
Stata STATA
Stata
Stata
STATA Computer Resource Center STATA
1985 2007 1.11.2,7.0
8.09.010.0 9.2

1.1
(1) http://www.pinggu.org/bbs/dispbbs.asp?boardID=67&ID=97705&page=2
stata9.rar
(2) D:/stata9
(3) setup >> D:/stata9>> Stata/SE

1.2
(1) Stata Stata


chrisccb@126.com

STATA

(2) D:/stata9>> wsestata>> sn


5

(3)
Prefs>>save windowing preference


chrisccb@126.com

STATA

Stata

DOS

review

Stata
Log Window
Help
(4) X
D: /stata9 C
c

1.3

STATA auto.dta
1.3.1
1
STATA
auto.dta
2 auto


chrisccb@126.com

STATA

12 74
AMC Concord
4099
3 X
1.3.2

use "D:\Stata9\auto.dta", clear


edit
auto
copy text
STATA STATA

. use "D:\Stata9\auto.dta", clear

. edit
auto X

1.3.3
Review
save review
content mydo
STATA STATA
mydo.do
1.3.4

STATA

1.4
STATA STATA

10 STATA


chrisccb@126.com

STATA

STATA 1
1.4.1
. help
STATA

. help summarize
: Help>>stata command
summarize help summarize
Description
Examples

. findit scat3, net


. search scat3, net
scat3 scat3 STATA

1.4.2
(1) STATA http://www.stata.com
(2) STATA http://www.stata.com/links/resources.html
(3) STATA http://www.stata-press.com
(4) STATA http://www.stata-journal.com/
(5) STATA
http://www.stata.com/support/faqs/
http://fmwww.bc.edu/gstat/docs/gsafaq.html
http://www.ats.ucla.edu/stat/stata/examples/default.htm

1.5
1.5.1
. di 5+9
. di 5-9
. di 5*9
. di 10/2
. di 10^2
. di exp(0)
. di ln(1)
. di sqrt(4)
di display
1

2

chrisccb@126.com

10

STATA

STATA
1.5.2

. use auto, clear


. sum price
. sum weight

. sum price weight


1.5.3

. scatter price weight


. line price weight, sort
1.5.4
x, (x=1,2,1000); y=x+100.
. clear
. set obs 1000
. gen x=_n
. gen y=x+100
1.5.5
. list n
lq
ctrl+break

1.6
1.6.1
1 1000 set more off set more
on
. set more off
. list
. set more on
. list
.q
1.6.2
. clear

1.6.3


chrisccb@126.com

11

STATA

. memory

. set memory 10m


1.6.4

. cd d:/stata9
dir
. dir
D mydata
mkdir
mkdir d:/mydata
cd
. cd d:/mydata
1.6.5
STATA
. list myvar
myvar
variable myvar not found
r(111);
myvar
List
r(111)

sum sun
. sun
unrecognized command: sun
r(199);
sun

1.7
1 clear, help, list, whelp, use, search, cd
2 2
3 8+2*ln(100)-e3/5^2


chrisccb@126.com

12

STATA

1.8
1.8.1 1
*============================chp1.do====================================
clear
//

set memory 10m


cd d:/stata8

//
//

use auto
// auto.dta
*
sum price
//
sum price weight
//

use /**/ auto, clear


sum weight ///
price
///
length
//
scatter price weight //
clear
set obs 1000
gen x=_n
gen y=x+100

//
// 1000
// 1 1000 x
// y,y 101 1100

/*
1 *STATA
2 /**/
3 ///
4 //
/**/
*/
*============================end=================================


chrisccb@126.com

13

STATA

1.8.2 2

help
search

cd

set memory 20m

clear
use
save

input
edit
infile
insheet

append
merge
xpose
reshape
generate
egen
rename
drop
keep
sort
encode
decode
order
by

describe
codebook
list
count
inspect
table
tabulate

display
log

STATA 20m

STATA


chrisccb@126.com

14

STATA 2

2
2.1
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]
[ ], command

2.2 command
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]
. cd d:/stata9
. use auto, clear

// auto.dta, clear

. summarize
/*
_all */
. summarize _all //
. sum
//sum summarize
. su
// su summarize s
.s
//
unrecognized command: s

summarize su
list l

list [varlist] [if] [in] [, options]


summarize [varlist] [if] [in] [weight] [, options]

list
list more,
set more on
1.6.1

2.3 varlist
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]
varlist
. cd d:/stata9
. use auto, clear
. sum price
//
. su p
//,
. su t
// ttrunk turn
STATA t
m ambiguous abbreviation
/
. sum tr tu
// trunk turn

chrisccb

15

STATA 2

. su t*

// t t*

()

_all _b byte _coef _cons double float if in int long _n _N _pi _pred _rc _se _skip using with

_ ,
_ 32
_ STATA _

2.4 by varlist
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]
, foreign
1 Foreign0 Domestic

. cd d:/stata9
. use auto, clear
. sum price weight
*
. by foreign: sum price weight //
*/
. sort price
//
. by foreign: sum price weight
*not sorted
/* by varlist
by sort price
foreign */
. sort foreign
//
. by foreign: sum price weight
*
. by foreign, sort: sum price weight
gsort

. sort - price
. sort foreign -price

//
/*

*/

2.5 =exp
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]

nprice price

chrisccb

16

STATA 2

10
. cd d:/stata9
. use auto, clear
. gen nprice=price+10
// nprice price+10
. list price nprice
//
/* generate( gen)
nprice, 10
. replace nprice=nprice-10
/* replace
nprice price */
. list price nprice
//

2.6 if exp
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]
if foreign==0 */
. cd d:/stata9
. use auto, clear
. list make price if foreign==0
* 1

. list make price if foreign==1 & price>10000


* 1
. list make price if foreign==1 | price>10000
* 1
. by foreign, sort: list make price if price>10000

2.7 in range
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]
10 10

. cd d:/stata9
. use auto, clear
. sort price
. sum price in 1/5
1/5 1 5 12345
10
. sum price in 1/10 if foreign==0

2.8 weight
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]
2005 640
score num 640


chrisccb

17

STATA 2

score

num

650

193

649

26

648

23

647

16

646

21

645

26

644

32

643

23

642

38

641

29

640

38

STATA
. clear
// STATA
. edit
paste

STATA
. sum score
// 640
sum

. sum score [weight=num] /* sum score


*/
. sum score [w=n]
//w weight n num

2.9 ,options
[by varlist:] command [varlist] [=exp] [if exp] [in range] [weight] [, options]

*/
. sum score, detail
. sum score, d
//d detail
1%5% 1%
10%50%
detail 5 5

*list
. cd d:/stata9
. use auto, clear
. list price in 1/30, sep(10)
// 10
. list price in 10/30, sep(2)
// 2
. list price, nohead
//

chrisccb

18

STATA 2

2.10
2


chrisccb

19

STATA 3

case

3.1 use
3.1.1
STATA .dta STATA
use
sysuse
. use auto,clear
// auto.dta
. cd d:/
// d:/
. use auto, clear
file auto.dta not found //, auto.dta d:/
r(601);
. sysuse auto,clear //

Auto : 1978
Bplong
Cancer
Census1980
Citytemp
Educ99gdp GDP
Gnp96 1967-2002 GNP
Lifeexp
Nlsw88
Pop2000 2000
Sp500 S&P500
Uslifeexp 1900-1999
Voter 1992

3.1.2
use
sysuse
. use nlswork, clear
file nlswork.dta not found


chrisccb@126.com

20

STATA 3

. use http://www.stata-press.com/data/r9/nlswork //
. webuse nlswork, clear // STATA
webuse http://www.stata-press.com/data
webuse
.

. use http://fmwww.bc.edu/ec-p/data/wooldridge/CEOSAL1
2.3 CEO
use *.dta.dta STATA

SAS SPSS SAS


SPSS STATA transfer

3.2
STATA
3.2.1
0129 +.
1,024 1024.
5
-5
5.2
5.2e+3
5.2e-2
5200 0.052. e
3
10 5.2e+3 5.2*10 =5200

0-

--------------------------------------------------------------------byte
-127
100
+/-1
1
int
-32,767
32,740
+/-1
2
long
-2,147,483,647
2,147,483,620
+/-1
4
float
-1.70141173319*10^38 1.70141173319*10^36
+/-10^-36
4

chrisccb@126.com

21

STATA 3

double -8.9884656743*10^307 8.9884656743*10^307


+/-10^-323
8

1 1.0000 ,(0.5,1.5),
(0.99995,1.00005)

. clear
. set obs 1
//
obs was 0, now 1 //,,
. gen a=1
// a, a 1
.d
/*d describ describ
a storage type float
*/
Contains data
obs:
vars:
size:

1
1
8 (99.9% of memory free)
storage display
type
format
float %9.0g

value
label

variable name
variable label
a
Sorted by:
Note: dataset has changed since last saved
. compress //
a was float, now byte
//a
.d
// a storage type byte
. replace a=101
/* a storage type int
byte 100*/
a was byte now int
(1 real change made)
. replace a=100
. compress
.d
// byte
. replace a=32741
// long , int 32740
. gen double b=1
// b
. recast double a
// a b
.d
// a b
3.2.2

chrisccb@126.com

22

STATA 3

244 str# str20


20 6

String
string
string
string

//

//
125.27
//125.27
$2,343.68
I love you

125.27 real()
destring 3.3.1
3.2.3
STATA 1960 1 1 0 1959 12 31
-1 2001 1 25 15000
16
1999 12 10
jan/10/2001
10jan2001
...
-15,000
--- 01dec1918
-31
---01dec1959
...
-1 --- 31dec1959
0 --- 01jan1960
1 ---02jan1960
...

chrisccb@126.com

23

STATA 3

31 ---01feb1960
...
15,000 ---25jan2001
3.2.4
.
. display 2/0
STATA .
.-9996
..-9996

. mvencode age,mv(-9996)
. mvdecode age,mv(-9996)

3.3
: destring1, destring2 tostring
*3.3.1 destring
*destring
.webuse destring1, clear
.des
/*storage type str#
#*/
Contains
data
from http://www.stata-press.com/data/r9/destring1.dta
obs:
10
vars:
5
3 Mar 2005 10:15
size:
240 (99.9% of memory free)
storage display
value
variable name type
format
label
variable label
id
str3
%9s
num
str3
%9s
code
str4
%9s
total
str5
%9s
income
str5
%9s
.sum
//
.gen nincom=incom+10 //
*type mismatch
// income 10
.destring, replace //replace
.sum
//
.gen nincom=income*1.3 // 30%!

chrisccb@126.com

24

STATA 3

.list nincom income


// 30%!
*---------------------------*destring2 data
.webuse destring2, clear
.des
// str
.list date
// date
date
-----------1. 1999 12 10
2. 2000 07 08
3. 1997 03 02
4. 1999 09 00
.destring date, replace
// date
*date contains non-numeric characters; no replace /*
*/
.destring date, replace ignore( )
/*
*/
date: characters space removed; replaced as long // long
.des
// date storage type long
.list date
//
date
---------1. 19991210
2. 20000708
3. 19970302
/* date price percent
*/
.destring price percent, gen(price2 percent2) ignore($ ,%)
.list
// price2 $percent2 %
date
price
price2 percent percent2
--------------------------------------------------------1. 19991210
$2,343.68
2343.68
34%
34
2. 20000708
$7,233.44
7233.44
86%
86
.d
// price2 percent2 double byte
*3.3.2 tostring
.webuse tostring, clear

/*
*/
// month

.des
.list
.gen date1=month+/+day+/+year //
type mismatch // month ,,
r(109);

chrisccb@126.com

25

STATA 3

.tostring year day, replace //


.des
//,
.gen date1=month+/+day+/+year //
.list
// date1/
.gen date2=date(date1,mdy)
/* date 1960 1 1
0 date1
mdy date1
*/
.list
// date2
* 1975 12 27

.di date(1975/12/27,ymd)

3.4 :format
/*format */
.webuse census10,clear
//
.des
// display format
storage display
value
variable name type
format
label
variable label
state
str14
%14s
State
region
int
%8.0g
cenreg
Census region
pop
long
%11.0g
Population
medage
float
%9.0g
Median age
*, stata %14s 14 ,%
.list in 1/4
//:
state
region
pop
medage
-----------------------------------------1. Alabama
South
3893888
29.3
2.
Alaska
West
401851
26.1
3.
Arizona
West
2718215
29.2
4. Arkansas
South
2286435
30.6
.format state %-14s // stata ,14
.list in 1/4
//,state
+------------------------------------------+
state
region
pop medage
-----------------------------------------1. Alabama
South
3893888
29.3
2. Alaska
West
401851
26.1
3. Arizona
West
2718215
29.2
4. Arkansas
South
2286435
30.6
.format region %-8.0g /*region
,.

chrisccb@126.com

26

STATA 3

.list in 1/4

// region

.format pop %11.0gc

/*pop %11.0g, c,
,c comma .*/
.list in 1/4
//,
state
region
pop
medage
------------------------------------------1. Alabama
South
3,893,888
29.3
2. Alaska
West
401,851
26.1
3. Arizona
West
2,718,215
29.2
4. Arkansas
South
2,286,435
30.6
5. California
West
23667902
29.9
* 11 ,
.format pop %12.0gc // pop 12
.list in 5
// pop
5. California West
23,667,902 29.9
.format medage %8.1f // medage
.list in 1/4
state
region
pop medage
-------------------------------------------1. Alabama
South
3,893,888
29.3
2. Alaska
West
401,851
26.1
3. Arizona
West
2,718,215
29.2
4. Arkansas
South
2,286,435
30.6
.gen id=_n // id 123
.replace id=9842 in 3 // id 9842
.list in 1/3
state
region
pop
medage
id
-------------------------------------------1. Alabama
South
3893888
29.3
1
2. Alaska
West
401851
26.1
2
3. Arizona
West
2718215
29.2
9842
.format id %05.0f
//
.list in 1/3
//, id 5
state
region
pop
medage
id
-------------------------------------------------1. Alabama
South
3893888
29.3
00001
2. Alaska
West
401851
26.1
00002
3. Arizona
West
2718215
29.2
09842

3.5 STATA input


3.5.1


chrisccb@126.com

27

STATA 3
id

economy

40

80

90

70

53

1 >>>>

var1 >> id>> label >>


var2 >> name>> label >>

>> student >>


chrisccb@126.com

28

STATA 3

STATA

3.5.2

id

name

economy

John

40

Chris

80

Jack

90

Huang

43

Tom

70

command (,
)

clear
//
input id str10 name economy
// str10.
1 John 40
//
//
2 Chris 80
3 Jack 90
4 Huang 70
5 Tom 53
end
//
save economy
// economy

3.5.3
1 do file editor
clear
//
input id str10 name economy
// str10.
1 John 40
//

chrisccb@126.com

29

STATA 3

2 Chris 80
3 Jack 90
4 Huang 70
5 Tom 53
end
//
save economy,erplace // economy
2 mydo
3

3.6 insheet
STATA

STATA

3.6.1 insheet
3origin.xls
3origin.csv( CSV
) STATA
. insheet using 3origin.csv, clear
3origin.xls3origin.txt

. insheet using 3origin.txt, clear

double
. insheet using 3origin.txt, double clear
3.6.2 infile
3origin.txt3origin.csv infile STATA

infile id str10 name gender minority economy math using origin.txt, clear

infile id str10 name gender minority economy math using origin.csv, clear
3.6.3 infix
0
origin.
114068
128052
029076
024390

chrisccb@126.com

30

STATA 3
037096
115385
028536
129565

infix gender 1 minority 2 economy 3-4 math 5-6 using origin.csv, clear

3.6.4 outsheet
STATA
acs outsheet

outsheet using myresult.txt


outsheet using myresult.asc
myresult.txt 26
Tab nonames
replace ,
outsheet using myresult.asc, nonames
outsheet using myresult.asc, nonames replace
3.6.4 transfer
Transfer
input File Type

transfer
http://www.pinggu.org/bbs


chrisccb@126.com

31

STATA 3

3.7 :label

pwd

pwd

dir

dir

mkdir

mkdir d:/mydata

cd

cd

cd d:/mydata

describ

des

rename

rename gender sex

label

//

label data

label data 2004

label var

label var name

label value
label define

label values gender genderlb


label define genderlb 1 "" 0 ""

note

note: 9 10

list

list id name

save

save mydata, replace

erase

erase mydata1.dta,replace

help command .
: mydata.dta D/mydata
mkdir label
/

3origin.xls
1

John

40

68

Chris

80

52

Jack

90

76

Huang

43

90

Tom

70

96

Han

53

85

Phillip

85

36

Jin

95

65

id name gender1
0 minority1 2 3
economy math

STATA


chrisccb@126.com

32

STATA 3

*===================chapter2.do==============================
*

/* D mydata
mkdir capture
STATA mydata
*/
clear
capture mkdir d:/mydata
* cd
cd d:/mydata
*3.7.1 rename
/* stata
3origin.dta*/
save 3origin, replace
/* var1, var2,...var6
name describ
*/
use 3origin, clear
des
// var1-var6
renpfix var v
// var v
rename v1 id
// id
rename v2 name
rename v3 gender
rename v4 minority
rename v5 economy
rename v6 math
des
//
*3.7.2 label data
/* label
2007 5632 */
label data 2007 5632
* notes
note: 2007 9 6
*
note
*3.7.3 label var
* label id
label var id
label var name

chrisccb@126.com

33

STATA 3

label var gender 1= 2=


label var minority
*3.7.4 label define label values
*
label define genderlb 1 "" 0 ""
list
// gender 0 1
label values gender genderlb
//
list
// gender
label define minoritylb 1"" 2 ""
label values minority minoritylb
list
*3.7.5 add modify
/* 3
*/
label define minoritylb 3
*
label minoritylb already defined
* minoritylb ,add
label define minoritylb 3 , add
list
label define minoritylb 3 dont know, add
/*dont know
*invalid attempt to modify label
3 ,modify*/
label define minoritylb 3 dont know, modify
list
*3.7.6 dir drop
label dir //
label list //
list
// minority """"dont know
label drop minoritylb //
label dir //
list
// minority 123
*3.7.7 save erase
compress
//
save mydata
// mydata
* mydata.dta, save mydata

save mydata

chrisccb@126.com

34

STATA 3

file mydata.dta already exists


*,
save mydata1
* replace
save mydata, replace
*erase
erase mydata1.dta
*
*===================end==============================

3.8
(1) st+
id

Name

Gender

age

Prov

(2) GDP
*.dta pv+

GDP

(3) input, end, save, exist, clear, list, help, use , search,
use webuse sysuse insheet infile infix


chrisccb@126.com

35

STATA 4

4
4.1

drop

drop math

keep

keep math

append

()

append using math

merge

merge id using math

reshape

reshape long inc,i(id) j(yr)

stack

stack a b c d, into(e f)

xpose

xpose, clear

help command
A

(drop/keep)

append

merge

A
B

4.2 :
4.2.1
4.1 mydata
student.dta, economy.dta
math.dta
mydata.dta
id

name

gender

minority

economy

math

John

40

68

Chris

80

52

Jack

90

76

Huang

43

90

Tom

70

96


chrisccb@126.com

36

STATA 4
6

Han

53

85

Phillip

85

36

Jin

95

65

student.dta
id

name

gender

minority

John

Chris

Jack

Huang

Tom

Han

Phillip

Jin

economy.dta
id

economy

40

80

90

43

70

53

85

95

math.dta
id

math

68

52

76

90

96

85

36

65

*- mydata student-------------------cd d:/mydata/


// d:/mydata
use mydata, clear // 3
drop economy math // economy math

chrisccb@126.com

37

STATA 4

save student, replace // student


*- mydata economy-------------------use mydata, clear // 3
keep id economy // id economy
save economy,replace // economy
*-- mydata math-------------------use mydata, clear
keep id math
save math,replace
4.2.2
4.2 mydata
female.dta male.dta

female.dta
id

name

gender

minority

economy

math

Jack

90

76

Huang

43

90

Phillip

85

36

Tom

70

96

John

40

68

male.dta
id

name

gender

minority

economy

math

John

40

68

Han

53

85

Jin

95

65

Chris

80

52

*---------------- mydata female-------------------use mydata, clear // 3


keep if gender==0 //
save female, replace
*---------------- mydata male-------------------use mydata, clear
drop if gender==0 //
save male, replace


chrisccb@126.com

38

STATA 4

4.3
4.3.1
4.3
female.dta male.dta
mydata1

*- female male mydata1-------use male, clear // male


append using female // female
save mydata1, replace
4.3.2
4.4 student.dta
math.dta, economy.dta mydata2.

*--------- mydata2--------use economy,clear //


sort id
//
save economy, replace //
use student,c clear
//
sort id
//
merge id using economy //
tab _merge
//3 1 2
drop _merge //_merge
sort id
//_merge
save mydata2,replace
use math,clear
sort id
merge id using mydata2 // mydata2 math
drop _merge
save mydata2, replace

4.4
4.4.1

reshape

reshape long inc,i(id) j(yr)

stack

stack a b c d, into(e f)

xpose

xpose, clear

chrisccb@126.com

39

STATA 4

4.4.2 :
4.5 mywide.dta 2003
2004 mylong.dta

mywide.dta
id

name

math2003

math2004

economy2003

economy2004

John

40

13

68

55

Chris

80

64

52

87

Jack

90

55

76

25

Huang

43

60

90

Tom

70

68

96

42

Han

53

10

85

89

Phillip

85

61

36

52

Jin

95

65

84

mylong.dta
id

name

year

math

economy

John

2003

40

68

John

2004

13

55

Chris

2003

80

52

Chris

2004

64

87

Jack

2003

90

76

Jack

2004

55

25

Huang

2003

43

90

Huang

2004

60

Tom

2003

70

96

Tom

2004

68

42

Han

2003

53

85

Han

2004

10

89

Phillip

2003

85

36

Phillip

2004

61

52

Jin

2003

95

65

Jin

2004

84

*--------- mywide --------use mywide, clear


reshape long math economy, i(id name) j(year) //,
save mylong, replace
*--------- mylong --------reshape wide
*

chrisccb@126.com

40

STATA 4

use mylong, clear


reshape wide math economy, i(id name) j(yearr) //,
save mywide2, replace
4.4.3 :
4.6
stata
21

87

23

97

58

56

46

21

79

17

26

42

59

26

29

94

89

35

16

81

62

27

80

76

26

89

11

67

10

37

45

48

40

71

57

37

13

22

72

69

10

96

22

93

*-----------------* STATA
stack var1-var6, into(x) clear
drop _stack

4.5 :
4.7

math.dta
id

math

68

52

76

90

96

85

36

65

newmath.dta
v1

v2

v3

v4

v5

v6

v7

v8

68

52

76

90

96

85

36

65


chrisccb@126.com

41

STATA 4

*-----------------use math,clear
xpose, clear

4.6

clear
input str15 x
"10*123"
"543*21"
"12*422"
"43532*32134"
"4349*1"
end
gen a=strpos(x,"*")
gen b=substr(x,1,a-1)
gen c=substr(x,a+1,.)
l

4.7
drop

keep

merge

append

reshape

xpose

stack

1i+
10
we+
id

name

gender
age

province

2 2000-2005 GDP
myhm+ 10
ourhm+
id

province gdp2000-gdp2005 income2000-2005

ourpv+
4 mylg+

chrisccb@126.com

42

STATA 4

id

province

year

1980

1981

pop

income

1980

1981

gdp


chrisccb@126.com

43

STATA 5

5
5.1 exp
STATA

>

<

>=

&

<=

==

sqrt()

!=

~=

~=

(~)^-
/*-+!=(~=),>,<,<=,>=,==,&,|

5.1.1
+-*/^-

x=4,y=2,-1

x + y x y
xy

. di (4+2^(4-2))/(2*4)

//di display

. di 4-2
// 2
. di 3*5
// 15
. di 8/2
//8 2 4
. di 2^3
//2 8
. di (2+3^(2-3))/sqrt(2*3) //

100
. sysuse auto, clear
. gen nprice=price+foreign*100 /* foreign 0 1
100 */
. list nprice price foreign

chrisccb@126.com

44

STATA 5

5.1.2
+
STATA
. scalar a= +STATA //
. scalar list a
//scalar a a
. scalar a=2 +3
//
type mismatch
r(109);
//
5.1.3

STATA ==

=
. di 3<5
// 1 3 5
. di 3>5
// 0 3 5
. di 3==4
// 0 3 4

65 65

age
38
.
65
42
18
80

. clear
. edit
STATA
. gen agegrp1=(age>=65)
65
. gen agegrp2=(age>=65) if age<.

. gen agegrp3=(age==65) if age<. // 65


. list // agegrp1 agegrp2 agegrp3 if age<.
age

Agegrp1

Agegrp2

Agegrp3

38

65

42


chrisccb@126.com

45

STATA 5
18

80

5.1.4
&|
10000 4000
. sysuse auto, clear
. list price foreign if price>10000 | price<4000 & forei==0
STATA &|,
. list price foreign if price>10000 | (price<4000 & forei==0)
, 10000 4000

. list price foreign if (price>10000 | price<4000) & forei==0

5.2 function

. help function
Type of function
See help
--------------------------------------+------------------------Mathematical functions
math functions
Probability distributions and
density functions
density functions
Random-number functions
random-number functions
String functions
string functions
Programming functions
programming functions
Date functions
date functions
Time-series functions
time-series functions
Matrix functions
matrix functions
STATA

abs(x)

abs(-9)=9

comb(n,k)

n k

comb(10,2)=45

exp(x)

exp(0)=1

fill()

int(x)

int(5.6) = 5, int(-5.2) = -5.

ln(x)

ln(1)=0


chrisccb@126.com

46

STATA 5
log10(x)

10

log10(1000)=3

mod(x,y)

= x - y*int(x/y)

mod(9,2)=1

round(x)

round(5.6)=6

sqrt(x)

sqrt(16)=4

sum(x)

uniform()

10

invnormal(uniform())

11

real(s)

string(n)

substr(s,n1,n2)

S n1 Substr(this,2,2)=is
n2

word(s,n)

s n

_n

_N

_pi

Work(this,3)=i

3.14159

5.3 math functions


5.3.1

. di sqrt(4)
// 2
. di sqrt(6+3)
// 3
. di abs(-100)
// 100
. di exp(1)
// e1 2.7182818
. di ln(exp(2))
// e2, 2
. di _pi
//_pi 3.1415927
. di cos(_pi)
//_pi -1

clear
set obs 5
// 5
gen x=_n
// x, 12345
gen y1=exp(x)
//
gen y2=ln(x)
//
gen y3=sin(exp(x) ) +cos(ln(x))
//
l
//
5.3.2

chrisccb@126.com

47

STATA 5

. di int(3.49)
. di int(3.51)
. di int(-3.49)
. di int(-3.51)

//int()
// 3
//-3
//-3

. di round(3.49)
. di round(3.51)
. di round(-3.49)
. di round(-3.51)
. di round(3.345,.1)
. di round(3.351,.1)
. di round(3.345,.01)
. di round(3.351,.01)
. di round(335.1,10)

//round() 3
// 4
//-3
//-4
// 3.3
// 3.4
// 3.35
// 3.35
// 340

. sysuse auto, clear


. gen nprice=price/10000
//
//
. gen nprice2=round(nprice,0.01)
. list nprice*
//
5.3.3 gen egen
clear
set obs 5
gen x=_n
// x, x 1 5
gen y=sum(x)
//
egen z=sum(x)
// y Z
egen r=rsum(x y z)
// x+y+z
egen havg = rowmean(x y z) // havg=(a+b+c)/3
egen hsd = rowsd(x y z)
// ab c
egen rmin = rowmin(x y z)
// x y z
egen rmax = rowmax(x y z) // x y z
list
// y z
egen avgx=mean(x)
//
egen medx=median(x)
//
egen stdx = std(x) // cvi=(xi-mx)/s, s=(xi-mx)/(n-1)
replace y=3 in 3
egen byte dxy = diff(x y) // x y differ 0 1
egen help egen

chrisccb@126.com

48

STATA 5

5.3.4
sysuse auto, clear
egen rmpg = rank(mpg) // mpg
sort rmpg
list mpg rmpg
//
egen highrep78 = anyvalue(rep78), v(3/5) /* rep78 34 5,
*/
list rep78 highrep78
clear
input a b
1 0
0 0
1 1
0 1
0 0
1 .
.
0
end
egen ab=group(a b)

/* a b a=0,b=0
,a=1,b=1 */
egen ab2=group(a b),missing //
l
//
a
b
ab
ab2
-----------------1. 1
0
3
3
2. 0
0
1
1
3. 1
1
4
4
4. 0
1
2
2
5. 0
0
1
1
-----------------6. 1
.
.
5
7. .
0
.
6
clear
set obs 100
// 100
gen age=_n
// age 12100
recode age (min/30=1) (30/60=2) (60/max=3),gen(agegrp) /*
agegrp, age 30
130 60 260 3*/


chrisccb@126.com

49

STATA 5

5.4 string functions

make3
sysuse auto, clear
gen str3 make3=substr(make,1,3) // make make3
list make*
,
a 1 2 3 4 a
0-1 na1=na2=

a
2
2
213
124
421
12
2
12

gen na1=strpos(a, "1")!=0

/*strops(s1,s2) s2 s1 ,
s1 s2 0
0 0-1

gen na2=strpos(a, "2")!=0


gen na3=strpos(a, "3")!=0
gen na4=strpos(a, "4")!=0
list
a
na1
na2
na3
na4
1. 2
0
1
0
0
2. 2
0
1
0
0
3. 123
1
1
1
0
4. 124
1
1
0
1
5. 124
1
1
0
1
6. 12
1
1
0
0
7. 2
0
1
0
0
8. 12
1
1
0
0
sysuse auto, clear
gen name2 = word(make,2) // name2 name

list n*
di word(this is a dog,4)

// dog


chrisccb@126.com

50

STATA 5

5.5 by

x
1
1
1
2
2

clear
edit
* STATA
y
1.1
1.2
1.3
2.1
2.2
gen n=_n
// n=12345
gen N=_N
// N=55555
gen z=y[1]
// z=y
l
x
y
n
N
z
----------------------1. 1
1.1
1
5
1.1
2. 1
1.2
2
5
1.1
3. 1
1.3
3
5
1.1
4. 2
2.1
4
5
1.1
5. 2
2.2
5
5
1.1
by x, sort: gen n1=_n
// n1 n n1 x
by x, sort: gen N1=_N
by x, sort: gen z1=y[1]
list
x
y
n
N
z
n1
N1
z1

1. 1

1.1

1.1

1.1

2. 1

1.2

1.1

1.1

3. 1

1.3

1.1

1.1

4. 2

2.1

1.1

2.1

5. 2

2.2

1.1

2.1

family.dta hhid age


STATA family.dta
hhid

age

86

42

36

chrisccb@126.com

51

STATA 5
1

57

28

42

40

1 hhsize2
id 113
mage4
1
nid

hhid

age

hhsize

id

mage

nid

28

15

49.8

36

13

49.8

42

12

49.8

57

14

49.8

86

11

49.8

22

29

40

23

29

42

21

29


STATA
use family, clear
by hhid,sort :gen hhsize=_N
// hhsize
by hhid,sort :gen id=_n+hhid*10
//
by hhid,sort: egen mage=mean(age) //
sort hhid age
//
by hhid: gen nid=_n
//
+---------------------------------------+
| hhid
age
hhsize
id
mage
nid |
|---------------------------------------|
1. |
1
28
5
11
49.8
1 |
2. |
1
36
5
12
49.8
2 |
3. |
1
42
5
13
49.8
3 |
4. |
1
57
5
14
49.8
4 |
5. |
1
86
5
15
49.8
5 |
|---------------------------------------|
6. |
2
5
3
21
29
1 |
7. |
2
40
3
22
29
2 |
8. |
2
42
3
23
29
3 |


chrisccb@126.com

52

STATA 5

use family, clear


bysort hhid (age): gen nid1=_n
// age
bysort hhid age: gen nid2=_n
// hhid ag e
list
//
hhid
age
nid1
nid2
-------------------------1. 1
28
1
1
2. 1
36
2
1
3. 1
42
3
1
4. 1
57
4
1
5. 1
86
5
1
-------------------------6. 2
5
1
1
7. 2
40
2
1
8. 2
42
3
1
webuse stan2, clear
expand 2 if transplant
// transplant==1
sort id
by id: generate byte posttran = (_n==2) /* posttran
0
1*/
by id: generate t1 = stime if _n==_N /* t1 id
stime.
gsort id


chrisccb@126.com

53

STATA 6

6
6.1

*============================begin=================================
clear
// STATA
version9 //
cd d:/stata9 //
capture log close /*
*/
log using myfile, replace // myfile
set more off
//
log off
//
*
sysuse auto, clear
sum
log on
//
tab forei
log close //
*============================end===================================
Log ,
*.smcl*.txt txt*.smcl replace

6.2 STATA

hello
hello
unrecognized command
STATA
hello STATA

*============================begin=================================
capture program drop hello

chrisccb@126.com

54

STATA 6

program hello
display ,
//
end
*============================end===================================
*
hello
* STATA
*,
* hello
sysuse auto, clear
list make price in 1/5
des
hello
describ list hello
stata
(program drop hello)
stata
STATA hello.do
.do STATA ()

do hello

,
STATA STATA
stata/ado/h hello.ado
.ado
hello
STATA
,
*/
*============================begin=================================
capture program drop hello
program hello
display as error `1
/*
*/
end
*============================end==================================
* hello
hello
hello
hello

chrisccb@126.com

55

STATA 6

*
*capture program drop programname
*program programname
*`1
*

capture program drop progname


program progname
command
end

capture

program hello
hello already defined
hello
*============================begin=================================
program drop hello
program hello
display ,
end
hello
*============================end=================================
stata stata

hello not found


stata program drop hello hello
capture
hello
*/
*============================begin=================================
capture program drop hello
program hello
display ,
end
hello
*============================end==================================


chrisccb@126.com

56

STATA 6

6.3 Macros: local/global

*============================begin====================================
sysuse auto, clear
list price length weight in 1/5
local v3 price length weight // price length weight v3
list `v3 in 1/5
/* list price length weight in 1/5`v3
*/
local cmd list
// list cmd
`cmd `v3 in 1/5
// list price length weight in 1/5
local pre pri
// pri pre
local suf ce
// ce suf
`cmd `pre`suf
// list price
tab rep`=26*3
// tab rep78, 26*3=78
* global
sysuse auto, clear
list price length weight in 1/5
global v3 price length weight // price length weight v3
list $v3 in 1/5
// list price length weight in 1/5
global cmd list
// list cmd
$cmd $v3 in 1/5
// list price length weight in 1/5
*============================end====================================

global a myvar
gen $a=oldvar
gen a=oldvar

gen myvar=oldvar
gen a=oldvar

local a myvar
gen `a=oldvar
gen a=oldvar

gen myvar=oldvar
gen a=oldvar

global a newvar
global i=2
gen $a$i=oldvar

gen newvar2=oldvar

local a newvar
local i=2
gen `a`i=oldvar

gen newvar2=oldvar


chrisccb@126.com

57

STATA 6
global b1 newvar
global i=1
gen ${b$i}=oldvar

gen newvar=oldvar

local b1 newvar
local i=1
gen `b`I=oldvar

gen newvar=oldvar

global b1 newvar
global a b
global i=1
gen ${$a$i}=oldvar

gen newvar=oldvar

local b1 newvar
local a b
local i=1
gen ``a`i=oldvar

gen newvar=oldvar

Global local
capt prog drop myprog
program myprog // myprog
// i
local i=""
// j
global j=""
di as txt "`i' " // i i
di as txt "$j" // j j
mysub
// mysub
di as error "`i' " // i i
di as error "$j"
// j
end
capt prog drop mysub
prog mysub
// myprog
// i
local i=""
global j="" // j
di as result "`i'"
// i i
di as result "$j" // j j
end
myprog // myprog


chrisccb@126.com

58

STATA 6

local

global

6.4
hello hello

captu prog drop listargs


prog listargs
di " `1' "
di " `2' "
di " `3' "
di " `4' "
end
listargs
listargs I love stata
listargs "I love stata"
local i "I love stata"
listargs `i'
listargs this is a test
listargs "this is a test"
listargs "this is" "a stata test"

captu prog drop listargs


prog listargs
args a b c d
di " `a' "
di " `b' "
di " `c' "
di " `d' "
end
listargs this is a test
listargs "this is a test"


chrisccb@126.com

59

STATA 6

6.5 scalar
scalar a=2
dis a+2
scalar b=a+3
di b
scalar s=hello
di s
clear
set obs 3
input a
1
3
5
end
scalar b=3
gen v1=a*b
list
input b
2
3
4
end
gen v2=a*b
list

// a 2
//a+2=2+2=4
//b=a+3=2+3=5
//5
//
//: hello

// a b( 3)

// v1 v2
//v1 v2 STATA

gen v3=a*scalar(b)
// b
list
STATA
scalar(varlist)
sysuse auto, clear
sum price
return list //
scalars:
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

chrisccb@126.com

60

STATA 6
local sum=r(sum)
di `sum

// sum

6.6 :tempvar tempfile


STATA

Clear
clear
set obs 5
tempvar x y
// x y
gen `x'=_n
//`x 1,2,3,4,5
gen `y'=_N
//`y 5,5,5,5,5
edit
//
gen z=`x'+`y'
// z
edit
// z
l
//__000000
__000001

preserve.restore
restore

*============================begin====================================
use auto, clear
preserve
//
keep price weight // price weight
save master, replace // master
drop weight
// weight weight
save part1,replace // part1
use master, clear
drop price
rename weight price
append using part1
erase master.dta
erase part1.dta
restore
// preserve auto
*============================end====================================
/* master part erase

*============================begin====================================
preserve

chrisccb@126.com

61

STATA 6
keep price weight
tempfile master part1
save `master
drop weight
save `part1
use `master, clear
drop price
rename weight price
append using `part1
restore
/*
*/
*============================end====================================/*

6.7
6.7.1

q1

oq2

A
A+B
=A/A+B

n
wimi pi i

i=1,2,n
mi

G1
n

i =1

i =1

G = 1 2 Bi = 1 pi (2Qi wi )
Qi =

(1)

wk

k =1

Qi 1 i B piwi 1 n 1
gini hbdata97.dta
hhid inc hhsize

6.7.2
*============================begin====================================
cd c:\\ex3
//

chrisccb@126.com

62

STATA 6
use hb97, clear
//
gen m=inc/hhsize
//m
sort m
//
egen tp=sum(hhsize)
// tp
egen tinc=sum(inc)
// tinc
gen p=hhsize/tp
// p
gen w=inc/tinc
// w
gen q=sum(w)
//
gen gini=1-sum(p *(2*q-w))
// gini
dis gini[_N]
//
* gen egen
*============================end====================================
*
*.26685518
* gini
*============================begin====================================
capture program drop gini
// gini
program gini
// gini
gen m=inc/hhsize
//m
sort m
//
egen tp=sum(hhsize)
// tp
egen tinc=sum(inc)
// tinc
gen p=hhsize/tp
// p
gen w=inc/tinc
// w
gen q=sum(w)
//
gen gini=1-sum(p *(2*q-w))
// gini
dis gini[_N]
//
end
*============================end====================================
use hb97,clear
gini
//
*.26685518

6.7.3 : args

inc cash food


gini
*/
*============================begin====================================
capture program drop gini
// gini
program gini
// gini
args inc hhs
// gini inc hhs
egen tinc=sum(`inc')
// gini

chrisccb@126.com

63

STATA 6
egen tp=sum(`hhs')
// gini
gen m=`inc'/`hhs'
// m
sort m
//
gen gini=1-sum(`hhs'/tp*(2*sum(`inc'/tinc)-`inc'/tinc))
//
dis gini[_N]
//
end
//
*============================end====================================
use hb97,clear
gini cash hhsize
//
*.35139242

6.7.4 `1 `2
STATA args */
*============================begin====================================
capture program drop gini
// gini
program gini
// gini
egen tinc=sum(`1')
// gini
egen tp=sum(`2')
// gini
gen m=`1'/`2'
// m
sort m
//
gen gini=1-sum(`2'/tp*(2*sum(`1'/tinc)-`1'/tinc))
//
dis gini[_N]
//
end
//
*============================end====================================
/*`1`2 inc hhs
gini */
use hb97,clear
gini inc hhsize
//
*.26685518
use hb97,clear
gini cash hhsize
*.35139242

//

*gini food hhsize


//
*tinc already defined
*STATA tinc

6.7.5
tp tinc mgini

STATA
*/
*============================begin====================================

chrisccb@126.com

64

STATA 6
capture program drop gini
program gini
tempvar tinc tp m gini
// tinc tp m gini
egen `tinc=sum(`1')
//tinc
egen `tp=sum(`2')
gen `m=`1'/`2'
sort `m
gen `gini=1-sum(`2'/`tp*(2*sum(`1'/`tinc)-`1'/`tinc))
dis `gini[_N]
//
end
*============================end====================================
use hb97,clear
gini inc hhsize
*.26685518
gini cash hhsize
*.35139242
gini food hhsize
*.21432981

//
//
//

6.7.6 STATA

STATA if
in */
*============================begin====================================
capture program drop gini
program gini
syntax varlist [if] [in] [,title(string)] //
tempvar tinc tp m gini
// tinc tp m gini
marksample touse
// 0/1 touse
preserve
// restore
quietly {
//
keep if `touse
// if
egen `tinc=sum(`1')
//tinc
if "`2'"=="" {
local 2=1
}
// 1
egen `tp=sum(`2')
gen `m=`1'/`2'
sort `m
gen `gini=1-sum(`2'/`tp*(2*sum(`1'/`tinc)-`1'/`tinc))
}
//
display as result "`title'" as error `gini'[_N]
restore

chrisccb@126.com

65

STATA 6
end
*============================end====================================
use hb97,clear
gini cash hhsize
*.35139242
gini cash
*.34467658
gini cash hhsize if ds==3
*.37227097
gini cash hhsize if ds==3,title()
*.37227097
gini cash hhsize if ds==1 in 1/200,title( 200 )
* 200 .30506945

*quietly noisily
di hello, guy
quietly di hello, guy
capture program drop bb
program bb
quietly {
noisily di hello, guy
}
end
bb
quietly bb

// quietly

//
//hello, guy


chrisccb@126.com

66

STATA 7

7
7.1 :while
7.1 12345

*============================begin=================================
capture drop count5
program count5
local i=1
// i 1
while `i<=5 { //`i 5{}
display `i
//`i
local i=`i+1
// i `i+1
}
end
*============================end==================================
count5
1
2
3
4
5
`i 1 1 5 1
i 1`i 2 2
5 2 i,,`i 6 5
{} end.


chrisccb@126.com

67

STATA 7

2
just one number
123
three numbers
321
three numbers in reversed order
.5 1 1.5
three different numbers
1 3 -2.17 5.12
four numbers in jumbled order
1/3
three numbers: 1, 2, 3
3/1
the same three numbers in reverse order
5/8
four numbers: 5, 6, 7, 8
-8/-5
four numbers: -8, -7, -6, -5
-5/-8
four numbers: -5, -6, -7, -8
-1/2
four numbers: -1, 0, 1, 2
1 2 to 4
four numbers: 1, 2, 3, 4
4 3 to 1
four numbers: 4, 3, 2, 1
10 15 to 30
five numbers: 10, 15, 20, 25, 30
1 2:4
same as 1 2 to 4
4 3:1
same as 4 3 to 1
10 15:30
same as 10 15 to 30
1(1)3
three numbers: 1, 2, 3
1(2)9
five numbers: 1, 3, 5, 7, 9
1(2)10
the same five numbers: 1, 3, 5, 7, 9
9(-2)1
five numbers: 9, 7, 5, 3, and 1
-1(.5)2.5
the numbers: -1, -.5, 0, .5, 1, 1.5, 2,
2.5
1[1]3
same as 1(1)3
1[2]9
same as 1(2)9
1[2]10
same as 1(2)10
9[-2]1
same as 9(-2)1
-1[.5]2.5
same as -1(.5)2.5
1 2 3/5 8(2)12
eight numbers: 1, 2, 3, 4, 5, 8, 10, 12
1,2,3/5,8(2)12
the same eight numbers
1 2 3/5 8 10 to 12 the same eight numbers
1,2,3/5,8,10 to 12 the same eight numbers
1 2 3/5 8 10:12
the same eight numbers

7.3 :forvalues

*============================begin=================================
forvalues i=1/5 {
display `i
//
}
*============================end==================================

chrisccb@126.com

68

STATA 7

3
*============================begin=================================
forvalues i=4 (-0.2) 0{ //
display `i
}
*============================end==================================
forvalues
forvalues lname = range {
commands referring to `lname'
}
range
#1(#d)#2
#1/#2
#1 #t to #2
#1 #t : #2
#

#1 #2 #d
#1 #2 1
#1 #2 #t - #1
#1 #2 #t - #1

7.2 1+2+3++100

*============================begin=================================
scalar s=0
//scalar s
forvalue i=1/100 {
scalar s=s+`i
// s
}
scalar list s
*============================end===================================

7.3 :foreach
5.3 wage1 nonwhite female married
numdepsmsa northcen south westconstrucndurman trcommputrade
servicesprofserv profocc clerocc servocc

tab varlist
*============================begin=================================
use http://fmwww.bc.edu/ec-p/data/wooldridge/ wage1, clear
tab nonwhite
tab female
tab married
tab numdep
tab smsa
tab northcen
tab south

chrisccb@126.com

69

STATA 7

tab west
tab construc
tab ndurman
tab trcommpu
tab trade
tab services
tab profserv
tab profocc
tab clerocc
tab servocc
*============================end==================================
while forvalues
foreach

*============================begin=================================
use wage1,clear
foreach v of varlist nonwhite-servocc {
tab `v
}
*============================end==================================
foreach
foreach lname {in|of listtype} list {
commands referring to `lname'
}

foreach lname in any_list {


foreach lname of local lmacname
{
foreach lname of global gmacname
{
foreach lname of varlist varlist
{
foreach lname of newlist newvarlist {
foreach lname of numlist numlist
{

7.4 student.dta, economy.dta, math.dta


*============================begin================================
use student, clear
foreach file in economy math {
append using `file
}
*

chrisccb@126.com

70

STATA 7

local flist economy math


// flist
foreach file in `flist {
append using `file
}
*============================end==================================
7.5()rice wheat flax maizeDollar
Lira Pound RMB
*============================begin=================================
local grains rice wheat flax maize
foreach x of local grains {
di `x
}
global money Dollar Lira Pound RMB
foreach y of global money {
di `y
}
*============================end=================================
7.6() b1,b2,b3,b4,b5

*============================begin=================================
clear
set obs 10
foreach v of newlist b1-b5 {
gen `v'=uniform()
}
*============================end==================================
7.7() 1 2 3 4 8 105
*============================begin================================
foreach num of numlist 1/4 8 105 {
di `num'
}
*============================end==================================
forvalues ,
2

7.4
7.8 5 10 i j
i+j
*============================begin================================
clear
set obs 10
forvalues i=1/5 {
//i 1, 2345

chrisccb@126.com

71

STATA 7

gen v`i'=. // v1, v1 v2,


forvalues j=2(2)8 { // j 2, 4,6,8
replace v`i'=`i'+`j' in `j' // 2 v1=1+2=3
}
}
*============================end==================================
v1
v2
v3
v4
v5
----- ------------------1. .
.
.
.
.
2. 3
4
5
6
7
3. .
.
.
.
.
4. 5
6
7
8
9
5. .
.
.
.
.
6. 7
8
9
10
11
7. .
.
.
.
.
8. 9
10
11
12
13
9. .
.
.
.
.
10. .
.
.
.
.

7.5
7.5.1
100 200

sysuse auto, clear


gen p1=price-100 if forein==0
replace p1=price+100 if foreign==1
gen p2=cond(foreign==0,(price-100),(price+100))

list p* forei
7.9
*============================begin================================
capture program drop odd
program odd
args num
if int(`num /2)!=(`num-1)/2 { //8-1/2 3 else
display num is NOT an odd number
}
else {
display num IS an odd number

chrisccb@126.com

72

STATA 7

}
end
*============================begin================================
odd 1
*num IS an odd number
odd 100
*num is NOT an odd number
7.10
*============================begin=================================
capture program drop check
program check
capture confirm variable `1
if _rc!=0 {
display `1 not found
exit
}
display the variable `1 exists.
end
*============================end==================================
use hb97,clear
check inc
the variable inc exists.
check exp
exp not found
7.5.2
7.11 6-500 235
*============================begin=================================
forvalues x=6/200 {
if mod(`x,2)==0 & mod(`x,3)==0 & mod(`x,5)==0 { //mod()
di the ALL common multiple of 2,3 ,and 5 is `x
}
}
*============================end==================================
the ALL common multiple of 2,3 ,and 5 is 30
the ALL common multiple of 2,3 ,and 5 is 60
the ALL common multiple of 2,3 ,and 5 is 90
the ALL common multiple of 2,3 ,and 5 is 120
the ALL common multiple of 2,3 ,and 5 is 150
the ALL common multiple of 2,3 ,and 5 is 180
7.12 6-500 235

chrisccb@126.com

73

STATA 7

*============================begin=================================
forvalues x=6/500 {
if mod(`x,2)==0 & mod(`x,3)==0 & mod(`x,5)==0 {
di the LEAST common multiple of 2,3 ,and 5 is `x
continue, break
}
}
*============================end==================================
the LEAST common multiple of 2,3 ,and 5 is 30

7.6
1
.
2 hb97 FGT


chrisccb@126.com

74

STATA 8

8
STATA9.0
MATA MATA STATA
STATA MATA
MATA

8.1
8.1.1

// A
matrix A= (1,0,1\2,1,0\-3,2,-5)
matrix list A // A
matlist A
// A, stata9
matrx B=(1+1,2*3/4 \ 5/2, 3^2)
matrix list B
matrix C=(2,3,4)
matrix E=(1\2\3)
matrix F=(4)
matrix rownames A= sex edu marriage
matrix colnames A=obs1 obs2 obs3
matrix list

8.1.2
5 3 A 0
matrix A=J(5,3,0)
6 I
matrix I=I(6)
3 5 R01
matrix R=matuniform(3,5)
matrix d=(1,4,9)
matrix D=diag(d)
matrix list D

//dD

8.1.3
R


chrisccb@126.com

75

STATA 8
mkmat varlist [if exp] [in range] [matrix(matname) nomissing ]
svmat [type] A [names(col|eqcol|matcol|string) ]
matname A namelist [rows(range) columns(range) explicit ]
*============================begin====================================
sysuse auto, clear
* foreign weight displ 5 X
mkmat foreign weight displ in 1/5, matrix(X)
matrix list X
* Y
mkmat foreign weight displ if fore==1, matrix(Y)
matrix list Y
matrix A= (1,0,1\2,1,0\-3,2,-5)
// A
svmat A
// A A1A2A3
list
svmat A, name(ccb)
// A ccb1ccb2ccb3

8.2
5-1

arlionEstimation with STATAMatrix

8.2.1
matrix A= (1,0,1\2,1,0\-3,2,-5)
matrix B=(4\3\7)
matrix C=(A,B)
matrix list C
matrix D= (10,9,25)
matrix E= (A\D)
matrix list E

chrisccb@126.com

76

STATA 8

8.2.2
mat e=(3,5\2,0)
mat t=(1,3\2,1)
mat r1=e+t
mat list r1
mat r2=e-t
mat list r2

//

//

mat e2=2*e
mat list e2

//

mat e3=e/10
mat list e3

//

8.2.3 Kronecker
mat w=e*t
mat list w

//

* a*b~=b*a
mat a=(2,3\1,-2\3,1)
mat b=(1,-2,-3\2,-1,0)
mat ab=a*b
mat list ab
mat ba=b*a
mat list ba
/**/
mat A=(1,2\3,4\5,6)
mat B=(7,8\9,0\1,9)
matrix H=hadamard(A,B)
mat list H
/* Kronecker


chrisccb@126.com

77

STATA 8
Kronecker A B */
mat ab2=a#b
mat list ab2
mat ba2=b#a
mat list ba2

8.3


chrisccb@126.com

78

STATA 8

arlionEstimation with STATAMatrix

8.3.1
mat b=(1,-2,-3\2,-1,0)
mat list b
mat b2=b`
//b2 b
mat list b2
/*
*/
matrix A= (1,0,1\2,1,0\-3,2,-5)
scalar a=trace(A)
// A b
scalar list

8.3.2
matrix B=inv(A)
mat list B

//B A

/* Ax=b
A=(1,-1,1,-2\2,0,-1,4\3,2,1,0\-1,2,-1,2)
b=(2\4\-1\-4) */
mat A1=(1,-1,1,-2\2,0,-1,4\3,2,1,0\-1,2,-1,2)
mat b=(2\4\-1\-4)

chrisccb@126.com

79

STATA 8
matrix B1=inv(A1)
mat X=B1*b
mat list X

//B A

mat a=(1,0,1\2,1,0\-3,2,-5)
scalar aa=det(a)
//det()
mat d=(1,-1,1,-2,2\2,0,-1,4,4\3,2,1,0,-1\-1,2,-1,2,-4)
mat dd=det(d)
scalar list

8.3.3
el(A,i,j)=A[i,j]
mat d=(1,-1,1,-2,2\2,100,-1,4,4\3,2,1,0,-1\-1,2,-1,2,-4)
scalar dd=d[2,2]
scalar ddd=el(d,2,2)
scalar list
mat d[1,3]=1000
mat list d

8.3.4Nullmat
mereg
mat A=I(3)
mat B=J(3,3,9)
mat list C
//C
mat C=(nullmat(C),A) //CC=A
mat list C
//C=A
mat C=(nullmat(B),A)
mat list C

//CBA
//C=BA

mat A=A/10
mat C=(nullmat(C),A) //CA
mat list C
//C=CA

8.3.5
matrix A= (1,0,1\2,1,0\-3,2,-5)
matrix e=vec(A)
//Ae
mat list e
matrix d=vecdiag(A)
matrix list d

//Ad


chrisccb@126.com

80

STATA 8

mat J=J(10,2,.)
scalar a=rowsof(J)
scalar b=colsof(J)
scalar list

//
//

8.4

XY
73
X \Y

-1

0.1

0.2

0.3

0.05

0.1

0.15

0.1

1 p{X!=0,Y=0} P{X<=0,Y<=0} P{XY=0} P{X=Y} P{|X|=|Y|}


2 Y=0 X X=0 Y
3 X Y
4=X+Y =XY
5 EXY
6 cov(x,y)
7 EX|Y=0
8 Z`=XYA=1-1/21W=AZEW=AEZ
9 cov(Z)
10
11 cov(W)=Acov(Z)A`
12 B=1-2/0-1cov(AX, BY)=Acov(X,Y)B`
13EX`AX=u`Au+tr(A) u=EX=cov(X)
*============================begin===================================
**X=x1,x2)'x1,x2
mat x1=(0,1,2)
mat x2=(-1,0,2)
**9,(x1=1,x2=2)
mat X=(0,-1\0,0\0,2\1,-1\1,0\1,2\2,-1\2,0\2,2)
**(0,-1),(0,0),(0,2);(1,-1)...22
mat p=(.1,.2,0,.3,.05,.1,.15,0,.1)
**9
**
mat EX=X*p'


chrisccb@126.com

81

STATA 8
**
mat dX=X-EX#J(1,9,1)
**
mat CovX=dX*(hadamard(dX,J(2,1,1)*p))'
. mat list CovX
**A
mat A=(1,-1\2,1)
**XY
mat Y=A*X
**Y
mat dY=Y-Y*p'#J(1,9,1)
mat list dY
**Y
mat CovY=dY*(hadamard(dY,J(2,1,1)*p))'
mat list CovY
** Cov(Y)=A*Cov(X)A'
mat CovY2=A*CovX*A'
mat list CovY2
**X
mat XAX=vecdiag(X'*A*X)
**
mat EXAX=XAX*p
**E(X'AX)=u'Au+tr(ACovX)
mat EXAX2=EX'*A*EX+trace(A*CovX)
mat list EXAX2
*============================end====================================
4=X+Y

-1

0.1

0.5

0.2

0.1

0.1

E=-1*0.1+0*0.5+1*0.2+2*0+3*0.1+4*0.1=0.8

*===========================begin====================================
capture program drop rv
prog rv

chrisccb@126.com

82

STATA 8
local s=0
matrix a=(0.1,0.2,0\0.3,0.05,0.1\0.15,0,0.1) // X Y
matrix x=(0,1,2)
// X
matrix y=(-1,0,2)
// Y
forvalues i=1/3 {
forvalues j=1/3 {
if uniform()>`s'& uniform()<=`s'+a[`i',`j'] {
scalar z=x[1,`i']+y[1,`j']
// Z=X+Y
}
local s=`s'+a[`i',`j']
}
}
end
simulate z ,reps(10000) nodots:rv
//10000
tab _simu
//
sum
//
*===========================end====================================


chrisccb@126.com

83

STATA 9

9
STATA10.0
EXCEL

a visual guide to stata graphics

9.1
//

*===========================begin====================================
sysuse auto , clear
twoway (scatter mpg weight if foreign==0)
///
/**/
(scatter mpg weight if foreign==1 , msymbol(Sh))
,
///
/**/
///
title(: )
subtitle(: 11574)
///
ytitle()
///
xtitle()
///
note(: )
///
text(35 3400 )
///
legend(title() label(1 ) label(2 ))
///

///

scheme(s1rcolor)
*===========================end====================================

9.1.1

chrisccb@126.com

84

STATA 9
graph-command (plot-command, plot-options) (plot-command , plot-options) , graph-options

graph-command plot-command,plot-options || plot-command , plot-options || , graph-options


graph-commandplot-command ,
||twoway
graph-commandscatterplot-command

twoway (scatter mpg weight) , title("")


//
twoway (scatter mpg weight , msymbol(Oh))
//
twoway (scatter mpg weight , msymbol(Oh)) , title("") //

sysuse auto, clear


graph twoway scatter mpg weight
twoway scatter mpg weight
scatter mpg weight
gr tw sc mpg weight
tw sc mpg weight
sc mpg weight

//graph
//twoway graph

9.1.2
STATA scatterlineareahistogram
bar
pie
functionmatrix
ts tslinelfitqfit
lowess
help graph
help towway

600

800

Total
1000

1200

1400

9.1 rf.dta , rainfall


year

use rf , clear
keep if id==1
save rfsz, replace
scatter rainfall year

line rainfall year

tw area rainfall year


1985

1990
Year

1995

85

600


chrisccb@126.com

800

Total
1000

1200

1400

1980

1980

1985

1990
Year

1995

2000

2000

STATA 9

2
9.2 51 popk propval100 division
allstates
vguse allstates ,clear
histogram
twoway histogram popk
kdensity
twoway kdensity popk
bar hbar
graph bar popk, over(division)
graph hbar popk, over(division)
box hbox
graph hbox popk, over(division)
graph box popk, over(division)
pie
graph pie popk, over(region)
matrix
graph matrix propval100 rent700 popden
dot
graph dot popk, over(division)
3
9.3 spjanfeb2001 close open
,tradeday
vguse spjanfeb2001, clear
twoway dropline close tradeday
//
tw spike close tradeday
//
tw dot close tradeday
//
tw connected close tradeday, sort
//
tw area close tradeday, sort
//
tw bar close tradeday,sort
/*XYgraph bar
X*/
twoway rarea high low tradeday, sort //
tw rline high low tradeday, sort
//
tw rconnected high low tradeday, sort //
tw rscatter high low tradeday, sort //
tw rcap high low tradeday, sort //
tw rspike high low tradeday, sort
//
tw rcapsym high low tradeday, sort

tsset tradeday
//Xtsset.
twoway tsline close, sort
//tsline

chrisccb@126.com

86

STATA 9
tw tsrline high low, sort

//

9.1.3 : title()
title()
subtitle()

use rfsz , clear


scatter rainfall year
,
title()

1400
1200
800

subtitle(1982-2001)

1982-2001

Total
1000

///
///
///

600

9.1.4

1980

1985

1990
Year

1995

2000

800
600
1980

1985

1990
Year

1995

2000

500
0
1980

1985

1990
Year

2000

10

5
1980

1985

1990
Year

1995

2000

Yield

87

Yield

Total
1000

1200

15

Total


chrisccb@126.com

1995
Yield

1400

Total

800

4
yield
line rainfall yield year
//
tw (line rainfall year
///
(line yield year)

mm(T/ha.)
Y

twoway (line rainfall year, yaxis(1))


///
(line yield year, yaxis(2))

Total/Yield
1000

1500

///
///
///
///

600

3
scatter rainfall year
,
plotregion(style(none))
yscale(noline)
xscale(noline)

Total
1000

1200

(2)
yyscale(off)xxscale(off),

///
scatter rainfall year
,
///
yscale(off)
///
xscale(off)
///
plotregion(style(none))

1400

(1)
scatter rainfall year

1200
Total
1000
800

///

600

5
ytitle()
xtitle()
use rfsz,clear
label var yield
tw (line rain year, yaxis(1) ytitle())
(line yield year, yaxis(2) xtitle())

1400

STATA 9

1980

5
ytick()
xtick()
line rainfall year
,
xtick(1982(1)2000)
ytick(600(100)1400)

1985

1990
Year

2000

800
700
600

1990

1995

2000

Total
1000

1200

1400

Year

800

9.4
scatter rainfall year
///
,
///
xlabel(1982 1990 1995 2000)
///
ylabel(600(100)1400)

1982

600

9.1.5 yline() xline()

Total
900 1000 1100 1200 1300 1400

///
///
///

6
ylabel()
xlabel()
line rainfall year
///
,
///
xlabel(1982 1990 1995 2000)
///
ylabel(600(100)1400)

help axis label option


34
scatter mpg weight , ysize(3) xsize(4)

1985

1990
Year

1995

2000

20
1980

1985

1990
Year
Jan

1995

2000

Feb

100

(1)
9.5STATA

line jan feb year

9.1.6 legend

Jan/Feb
40
60

80

100

1980

80

///

40

Jan/Feb
60

88

20


chrisccb@126.com

2
line jan feb year

1995

1980

1985

1990
Year

1995

2000

STATA 9

///

legend(off)

20

Jan/Feb
40
60

80

100

3 legend(label())

line jan feb year


///
,
///
legend(label(1 ) label(2 ))

label var jan


label var feb
line jan feb year

1980

1985

1990
Year

20

Jan/Feb
40
60

80

100

1980

1985

1990
Year

1995

2000

100

ring(0)
line jan feb year
///
,
///
legend(pos(1)
///
ring(0)
///
label(1 )
///
///
label(2 )
col(1))
//col(1)

2000

4 legend(position())
12
position(3) position(5)
position(12)
line jan feb year
///
,
///
legend(pos(12) label(1 ) label(2 ))

1995

20

40

Jan/Feb
60

80

1980

1985

1990
Year

1995

2000

1200
600

800

Total
1000

scatter rain year


,
note()

1400

9.1.7 note()

1980

9.2

1985

1990
Year

1995

2000

9.2.1
msymbol()


chrisccb@126.com

89

STATA 9
O
Oh
o

D
Dh
d

S
Sh
s

T
Th
t

oh

dh

sh

th

X
x

% in poverty
20

9.6

vguse allstates, clear


scatter pov statefips [fw=pop], msymbol(oh)

25

30

10

15

scatter pov statefips [fw=pop], msymbol(o)


mfcolor(green) mlcolor(red)

20

40

60

state code

30

30

scatter pov statefips, mlabel(stateab)

MS

25

25

LA

WV
KY

SC
TN
SD

GA

AZ

ND
NC

15

MO
CA
CO

FL

AK

10

DE

TX

OK
MT

ID

MI
KS
ME
IA
ILIN
MN
MA
HI

% in poverty
20

DC

NE
NV

OR
NY OH
PA RI

VAWA
UT
VT

WY

15

% in poverty
20

NM
AR
AL

WI

NH
NJ

CT

10

MD

20

40

60

state code

20

40

60

state code

vguse allstates,clear
twoway (scatter ownhome borninstate if stateab=="DC", mlabel(stateab)) ///
(scatter ownhome borninstate), legend(off)
connect()
.
l
L X
m
s
J
||
II
c(l)c(l[-])
l

chrisccb@126.com

90

STATA 9
l[_]
l[-]
l[.]
l[#]

1300

1350

1400

twoway line

1250

price

open

1200
1150

sysuse sp500,clear
gen n=_n
twoway ///
(line open close n in 1/50 , sort clpattern( -))
///
, ///
plotregion(margin(zero)) ///
title("twoway line") ///
xtitle("date") ///
ytitle("price") ///
legend(label(1 "open") label(2 "close")
order(2 1) ///
ring(0) pos(8)) ///
text(1300 25 "open")

close
0

10

open
20

30

40

date

9.2.2
9.7nsw9 (division)(propval100)
allstates.dta
80

% homes over $100K

70

North

South

West

66.57

60

53.00

52.46

50
40
28.91

30

19.85

18.46

20

11.60

10.01

11.35

10

Pa
ci
fic

ou
nt
ai
n

.S
.C
.
W

E.
S.
C

S.
At
l.

.C
.N
W

E.
N
.C
.

At
l
M
id

N
.E
ng
.

Region

vguse allstates, clear


gsort nsw division
list propval100 nsw division

graph bar propval100, over(nsw) over(division)


chrisccb@126.com

91

50

20

mean of propval100
40
60

80

STATA 9

North
South
West
North
South
West
North
South
West
North
South
West
North
South
West
North
South
West
North
South
West
North
South
West
North
South
West

N. Eng. Mid Atl E.N.C. W.N.C. S. Atl. E.S.C. W.S.C.MountainPacific

20

mean of propval100
40
60

80

nofill

graph bar propval100, over(nsw) over(division) nofill

North

North

North

North

South

South

South

West

West

N. Eng. Mid Atl E.N.C. W.N.C. S. Atl. E.S.C. W.S.C.MountainPacific

20
0

use allstates, clear


gen yNorth=propval100 if nsw==1
gen ySouth=propval100 if nsw==2
gen yWest=propval100 if nsw==3
graph bar
///
yNorth ySouth yWest, ///
over(division) nofill

mean of propval100
40
60

80

asyvars
y ynorth ysouth ywest
graph bar propval100, over(nsw)
over(division) nofill asyvars

N. Eng. Mid Atl E.N.C. W.N.C. S. Atl.

E.S.C. W.S.C. Mountain Pacific

North
West

South

80
70
60

graph bar propval100, over(nsw)


over(division) nofill asyvars ///

50
40
30
20


chrisccb@126.com10
0

92
N. Eng. Mid Atl E.N.C. W.N.C. S. Atl.

E.S.C. W.S.C. Mountain Pacific

Region
North
West

South

STATA 9
ytitle()
ylabel(0(10)80)
b1title(Region)

///
///

graph bar propval100, over(nsw) over(division) nofill asyvars ///


ytitle() ylabel(0(10)80) b1title(Region) ///
legend(rows(1) position(1) ring(0))
80

North

South

West

70

60
50
40
30
20
10
0

N. Eng. Mid Atl E.N.C. W.N.C. S. Atl.

E.S.C. W.S.C. Mountain Pacific

Region

graph bar propval100, over(nsw)


///
over(division, label(angle(45))) /*45*/
///
nofill asyvars ytitle("") ylabel(0(10)80, angle(0)) b1title(Region)
legend(rows(1) position(1) ring(0))
///
blabel(bar, format(%4.2f)) //
80

North

70

South

///

West

66.57

60

53.00

52.46

50
40
28.91

30

19.85

18.46

20

11.60

10.01

10

11.35

Pa
ci
fic

ou
nt
ai
n

.S
.C
.
W

E.
S.
C

S.
At
l.

.C
.N
W

E.
N.
C
.

At
l
M
id

N
.E

ng
.

Region

clear
input str5 age m f
16-24 .9 .2
25-44 .8 .8
45-66 3.8 2.9

chrisccb@126.com

93

STATA 9

10

67-79 8.2 5.4


80+ 9.1 7.2
end
//
graph bar m f ///
// graph bar
, ///
over(age) ///
//
title() ///
b1title("Age") ///
//
ytitle() ///
legend( label(1 "Males") label(2 "Females") ) ///
bar(2 , bfcolor(gs3)) //

16-24

25-44

45-66

67-79

80+

Age
Males

Females

9.2.3
9.8 10

*============================begin=================================
clear
set memory 64m
input x1-x10
142.3
134.4
150.3
141.9
143.5
138.1
142.9
140.9
134.7
141.2
135.5
140.2

156.6
148.8
133.1
140.7
139.2
140.2
134.9
141.4
138.5
148.9
144.4
145.4

142.7
137.9
142.7
141.2
144.7
137.4
143.6
160.9
138.9
154.0
143.4
142.4

145.7
151.3
143.9
141.5
139.3
145.1
142.3
154.2
137.7
147.7
137.4
148.9

138.2
140.8
151.1
148.8
141.9
145.8
125.9
137.9
138.5
152.3
143.6
146.7

141.6
149.8
144.0
140.1
147.8
147.9
132.7
139.9
139.6
146.6
150.0
139.2

142.5
145.2
145.4
150.6
140.5
150.8
152.9
149.7
143.5
132.1
143.3
139.6

130.5
141.8
146.2
139.5
138.9
144.5
147.9
147.5
142.9
145.9
146.5
142.4

134.5
146.8
143.3
146.4
134.7
137.1
141.8
136.9
129.4
146.7
149.0
138.7

148.8
135.1
156.3
143.8
147.3
147.1
141.4
148.1
142.5
144.0
142.1
139.9

end
stack x1-x10,into(y) clear
ren _sta n
forvalues i=1/10 {
replace n=`i' if y>124+`i'*4&y<124+4*(`i'+1)
}
hist y,norm
*============================end==================================


chrisccb@126.com

94

.02

Density
.04

.06

.08

STATA 9

130

140

150

160

sysuse auto, clear


ladder mpg
gladder mpg
square

identity

sqrt

log

1/sqrt

inverse

1/square

1/cubic

Density

cubic

Mileage (mpg)

cubic

square

-10000 0 10000200003000040000

identity
10 20 30 40

0 500
1000
1500
2000
-500

500

2.5 3 3.5 4
3

2.5

3.5

1/square
-.008
-.006
-.004
-.0020

-.08-.06-.04 -.02

inverse

-.08

-.06

-.04

-.02

-.006

-.004

10

-.002

15

20

25

30

35

1/sqrt

-.3 -.25 -.2 -.15

log

3 4 5 6 7

sqrt

1000

-.3

-.0006
-.0004
-.00020.0002

-20000
020000
40000
60000
80000

Histograms by transf ormation

-.25

-.2

-.15

1/cubic

-.0004-.0003-.0002-.0001

.0001

Mileage (mpg)
Quantile-Normal plots by transf ormation

9.2.4
9.10 95%

*============================begin=================================
sysuse nlsw, clear

chrisccb@126.com

95

STATA 9
graph hbox wage, over(grade) asyvar nooutsides legend(rows(2))

*============================end=================================

5
4
12

5
13

10
hourly wage
6
14

7
15

15
8
16

9
17

20
10
18

11

excludes outside values

9.2.5
9.11:
twoway ///
(function y=normden(x) , range(-3.5 3.5) ///
droplines(-1.96 -1 0 1 1.96)) ///
, ///
title(twoway function) ///
plotregion(margin(zero)) ///
yscale(off) ylabel(, nogrid) ///
xlabel(-3 -1.96 -1 0 1 1.96 3 , format(%4.2f)) ///
xtitle("Standard deviations from mean")

twoway function

-3.00

-1.96

-1.00
0.00
1.00
Standard deviations from mean

1.96

3.00

9.3 by(varname)

vguse allstates ,clear


twoway (scatter propval100 popden) (lfit propval100 popden)(qfit propval100 popden)
twoway (scatter propval100 popden) (mspline propval100 popden) ///
(fpfit propval100 popden) (mband propval100 popden)(lowess propval100 popden)
twoway (lfitci propval100 popden) (scatter propval100 popden)
by(varname) matrix star , graph
bar box

chrisccb@126.com

96

STATA 9

10

15

500 1000 1500 2000

10

15

500 1000 1500 2000

Rescale by()

9.12: rf.dta (yield)(rainfall)

use rf, clear


twoway (bar rainfall year, yaxis(2))
///
(scatter yield year, yaxis(1)) ///
(lfit yield year, yaxis(1)) ,
///
by(id) legend(row(1))

1980

1985

1990

1995

2000

1980

1985

1990

1995

2000

Year...
Total

Yield

Fitted values

Graphs by id

1.4
2.6
.8
.2
2

1.4
2.6
.8
.2
2

GDP/

7.2 10 GDP

2000

2000

2000

year
Graphs by province

use ourhm, clear


twoway rcapsym ni income year, xlabel(2000(2000)2004) ylabel(0.2(0.6)2.4) by(prov)

chrisccb@126.com

97

STATA 9

9.4
1

sysuse auto, clear


set scheme s2color
//see help scheme_s2color
sc mpg weight
set scheme s2mono
sc mpg weight
set scheme s2manual
sc mpg weight
set scheme s1color
sc mpg weight
set scheme s1mono
sc mpg weight
set scheme s1rcolor
sc mpg weight

set scheme s1manual


sc mpg weight
set scheme sj
sc mpg weight
set scheme economist
sc mpg weight
2
graph save "c:\ex7\rf.gph"
graph save "c:\ex7\rf.gph" , asis replace
asis
replace
3
graph use "c:\ex7\rf.gph" [, scheme(s1)]
4
graph display [, scale(1.2) ysize(3) xsize(5) scheme(s1)]


chrisccb@126.com

98

STATA 9

9.5
STATA
http://www.ats.ucla.edu/stat/stata/Library/GraphExamples/default.htm


chrisccb@126.com

99

STATA

10

2000 1000

clear
mata
R=uniform(1000,2000)
R[1,.]=R[1,.]:>uniform(1,2000)
for (i=2;i<=2000;i++) {
R[i,.]=(uniform(1,2000):>mean(R))
}
(mean(R))'

10.1
01 uniform()
di uniform()
di uniform()
di uniform()
1
0123456789

di int(10*uniform())
(0-99)
di int(100*uniform())
a,b
a+(b-a)*uniform()
a,b
a+int((b-a)*uniform())

set seed #

*============================begin====================================
clear
set obs 10
gen x1=uniform()
gen x2=uniform()
// x1 x2
set seed 1234
gen y1=uniform()
set seed 1234

chrisccb@126.com

100

STATA

gen y2=uniform()
gen y3=uniform()
// y1 y2 y3
set seed 5634
gen z1=uniform()
set seed 1234
gen z2=uniform()
// z2 y1,y2 z1 z2
list
*============================end====================================
STATA
search rnd, net
rndbin 1000 0.5 1 // 1000 0-1 1 0.5()

10.2
simulation

1
10 3 3

1
2
3

z 0.5
z

z 0-9 0.1
z
z

z 10
z 1 0
z 10 10010001000000 =/
0.826

*============================begin====================================
capt prog drop seq3
prog seq3,rclass
//rclass return r()
version 9
drop _all
// clear
set obs 10
// 10

chrisccb@126.com

101

STATA

tempvar x y z
// x,y,z
gen `x=int(10*uniform())
// 10 019
gen `y=(mod(`x,2)==0)
// y=0;y=1
gen `z=0
// Z=0
forvalues i=3/10 {
replace `z=1 if `y==`y[_n-1] & `y==`y[_n-2] in `i' // z=1
}
sum `z
return scalar max=r(max)
//z 1
end
simulate max=r(max),reps(10000) nodots:seq3
// 1
sum
*============================end====================================

clear
set obs 10
// 10
gen y=0
gen z=0
capt prog drop seq3
prog seq3
replace y=uniform()>0.5
// y=0;y=1
replace z=0
forvalues i=3/10 {
replace z=1 if y==y[_n-1] & y==y[_n-2] in `i'
}
sum z
end
simulate r(max),reps(10000) nodots:seq3
// 1
sum

capt prog drop seq3


program seq3
drop _all
// clear
rndbin 10 0.5 1
gen z=0
// Z=0
forvalues i=3/10 {
replace z=1 if xb==xb[_n-1] & xb==xb[_n-2] in `i' // z=1
}
sum z
end
simulate max=r(max),reps(10000) nodots:seq3
// 1

chrisccb@126.com

102

STATA

sum
*MATA
*============================begin====================================
mata
A=uniform(10000,10):>0.5 //,
B=J(10000,1,0)
//, 0. 1
for (j=1;j<=rows(A);j++) {
// j
for (i=3;i<=cols(A);i++) {
// j i
if ( A[j,(i-2,i-1,i)]==(0,0,0) | A[j,(i-2,i-1,i)]==(1,1,1) ) {
B[j,1]=1
//, 1
break
}
}
}
mean(B)
//
end
*============================end====================================

10.3
2

0.49

00010249=
49505199=

3
100
6905 16 48
17 8717 648987


0.867
*============================begin====================================
capt program drop girl
program girl, rclass
drop _all
set obs 3
gen x=int(100*uniform())
gen y=(x<49)
// y=1,y=0

chrisccb@126.com

103

STATA

sum y
return scalar max=r(max)
// max 1 0
end
simulate max=r(max),reps(10000) nodots:girl
sum
*============================end====================================

clear
set obs 3
gen y=0
capt program drop girl
program girl
replace y=(int(100*uniform())<49) // y=1,y=0
sort y
scalar girl=y[_N]
// girl 1 0
end
simulate girl, reps(10000) nodots:girl
sum

.
*============================begin====================================
capt program drop girl
program girl
mat A=matuniform(1,3)
scalar girl=1
if A[1,1]>0.49 & A[1,2]>0.49 & A[1,3]>0.49 {
scalar girl=0
// 0
}
end
simulate girl,reps(10000) nodots:girl
tab _sim
*============================end====================================
*============================begin====================================
mata
A=uniform(10000,3):<0.49
B=J(10000,1,1)
for (i=1;i<=rows(A);i++) {
if (A[i,.]==(0,0,0)) {
B[i,1]=0
// 0

chrisccb@126.com

104

STATA

}
}
mean(B)
end
*============================end====================================

10.4
3

0.90.60.4
70%

1
0=
1-9=
2
0-5=
6-9=
3
0-6=
7-9=
3
0-4=
5-9=

0.558
*============================begin====================================
/*0.90.60.4
70%
*/
capt program drop surv
program surv,rclass
drop _all
set obs 1
gen z=1
gen x1=int(10*uniform())
if x1==0 {
replace z=0
}

chrisccb@126.com

105

STATA

else {
gen x2=int(10*uniform())
if x2<6 {
gen x3=int(10*uniform())
if x3>6 {
replace z=0
}
}
else {
gen x4=int(10*uniform())
if x4>4 {
replace z=0
}
}
}
sum z
return scalar max=r(max)
end
simulate max=r(max),reps(10000) nodots:surv
sum
*============================end====================================

*============================begin====================================
capt program drop surv
program surv
scalar z=1
if uniform()<0.1 {
scalar z=0
}
else {
if uniform()<0.6 {
if uniform()>=0.7 {
scalar z=0
}
}
else {
if uniform()>=0.5 {
scalar z=0
}
}
}
end
simulate z,reps(10000) nodots:surv

chrisccb@126.com

106

STATA

sum
*============================end====================================

10.5
X [10,30]
[10,30] 500
100
300 9280
X

f ( x ) = 20
0

10 x 30

a Z

500 X 100 ( a X )
Z =
500a + 300 ( X a )
600 X 100a
=
300 X + 200a

10 X a
a X 30

E ( Z ) = Z ( x ) f ( x ) dx

10

= 0dx +

30

10

30

10

1
Z ( x ) dx + 0dx
30
20

1
Z ( x) d
20

1 a
( 600 x 100a )dx +
20 10
1 0
+ ( 300a + 200 x )dx
20 a
a
1
300 x 2 100ax +
=
10
20
1
+ 150 x 2 + 200ax
20

= 7.5a 2 + 350a + 5250 9280

7.5a 2 350a + 4030 0

( 3a 62 )( 2.5a 65) 0

2 62
65
20 =
a
= 26
3 3
2.5

21 9280
*============================end====================================

chrisccb@126.com

107

STATA

captu program drop goods


program goods
scalar x=10+int(20*uniform())
if `1'>=x {
scalar z=500*x-100*(`1'-x)
}
else {
scalar z=500*`1'+300*(x-`1')
}
end
set more off
quietly forvalues i=10/30 {
simulate z,rep(1000) nodots: goods `i'
quietly sum
scalar z`i'=r(mean)
}
scalar list
*============================end====================================

10.6
Asian stochastic beetle120%
30% 1 50% 2
2

23 1/2
60
4

0.1

0.4

0.4

0.1
4

X Y
[10,20]
1000
500

f ( x, y ) = f X ( x ) f Y ( y )

1 10 x 20

= 100 10 y 20

0
chrisccb@126.com

108

STATA

1000Y

Z =
1000 X + 500 (Y X )
YX
1000 X
=
500 ( X + Y ) Y > X
E (Z ) =

= 1000 y *
D1

Z ( x ) f ( x, y ) dxdy

1
dxdy + 500 ( x + y )dxdy
100
D2
y

= 10 dy ydx + dy 5 ( x + y )dx
20

10

20

20

10

10

20

= 10 y ( 20 y ) dy +
20

10

20 3

+ 5 y 2 10Y 50 dy
10
2

= 10 10 y 2 y 3 +
3 10

20

+ 5 y 3 5 y 2 50 y
2
10
20000
=
+ 5*1500
3
14167

10.7

Asian stochastic beetle120%


30% 1 50% 2
2

*===========================begin====================================
capture prog drop bb
prog bb,rclass
local beetle=`1'
while `beetle'<500 & `beetle'>0 {
drop _all
set obs `beetle'
tempvar x y
gen `x'=uniform()
gen `y'=1
replace `y'=2 if `x'<0.5
replace `y'=0 if `x'>0.8

chrisccb@126.com

109

STATA

quietly sum `y'


local beetle=r(sum)
}
noisily display as error `beetle'
end
set more off
quietly bb 10
*===========================end====================================
23 1/2
60
*===========================begin===================================
captu prog drop birth
prog birth
drop _all
set obs 60
tempvar y
gen `y'= int(365* uniform())
sort `y
scalar z=0
forvalues i=1/59 {
if `y'[`i']==`y'[`i'+1] {
scalar z=1
continue, break
}
}
end
simulate "birth" z,reps(100)
sum
*===========================end====================================
4

0.1

0.4

0.4

0.1
4

*===========================begin===================================
captu prog drop wns
prog wns
drop _all
set obs 4
tempvar x y

chrisccb@126.com

110

STATA

gen `y'= uniform()


recode `y' (0/0.1=1) (0.1/0.2=2) (0.2/0.6=3) (0.6/1=4), gen(`x')
sort `x'
scalar z=1
forvalues i=1/4 {
if `x'[`i']==`x'[`i'+1] {
scalar z=0
continue, break
}
}
end
simulate "wns" z,reps(1000)
sum
*===========================end====================================

*===========================begin===================================
captu prog drop child
prog child
drop _all
set obs 3
tempvar y
gen `y'=int(100*uniform())
scalar boy=0
scalar girl=0
if `y'[1]<49 {
scalar girl=1
if `y'[2]<49 {
scalar girl=2 //
if `y'[3]<49 {
scalar girl=3 //
}
else {
scalar boy=1 //21
}
}
else {
scalar boy=1 //11
}
}
else {

chrisccb@126.com

111

STATA

scalar boy=1 //01


}
end
simulate "child" boy=boy girl=girl,reps(1000)
sum
*===========================end====================================

*===========================begin===================================
captu prog drop child
prog child, rclass
drop _all
set obs 3
tempvar y b g
gen `y'=int(100*uniform())
gen `b'=0
gen `g'=0
replace `b'=1 if `y'>=49
sum `b'
scalar boy=r(sum)
replace `g'=1 if `y'<49
sum `g'
scalar girl=r(sum)
end
simulate "child" boy girl,reps(1000)
sum
*===========================end====================================
X Y
[10,20]
1000
500
X Y X=[1020]Y=[1020]
*============================begin====================================
capture program drop pf
prog pf
scalar x=10+10*uniform()
scalar y=10+10*uniform()
if x>=y {
scalar z=1000*y
}
else {
scalar z=500*(x+y)
}
end
simulate " pf" z,reps(10000)

chrisccb@126.com

112

STATA

sum
*============================end====================================
14153.12
X=101120y=101120

*============================begin==================================
capture program drop pf
prog pf
scalar x=10+int(11*uniform())
scalar y=10+int(11*uniform())
if x>=y {
scalar z=1000*y
}
else {
scalar z=500*(x+y)
}
end
simulate " pf" z,reps(10000)
sum
*============================end====================================
14102.65

clear
mat A=J(11,11,.)
forvalue i=1/11 {
forvalue j=1/11 {
if `i'>=`j'{
mat A[`i',`j']=1000*(9+`i')
}
else if `i'<`j' {
mat A[`i',`j']=500*(18+`i'+`j')
}
}
}
mat list A
mat a=J(1,11,1)
mat C=a*A*a'/121
mat list C
* 15909.091
* 1
clear
mat A=J(101,101,.)

chrisccb@126.com

113

STATA

forvalue i=1/101 {
forvalue j=1/101 {
if `i'>=`j'{
mat A[`i',`j']=1000*(10+(`i'-1)/10)
}
else if `i'<`j' {
mat A[`i',`j']=500*(20+(`i'-1)/10+(`j'-1)/10)
}
}
}
mat a=J(1,101,1)
mat C=a*A*a'/10201
mat list C
15841.584
*============================end====================================


chrisccb@126.com

114

STATA 11

11

Binomial(n,k,p)

Cnkpk(1-p)n-k

normal(z)

normalden(z)
normalden(z,s) = normalden(z)/s
normalden(x,m,s) = normalden((x-m)/s)/s

lnnormal(z)

lnnormalden(z)
lnnormalden(z,s)=lnnormalden(z)-ln(s)
lnnormalden(x,m,s)=lnnormalden((x-m)/s)

chi2(n,x)

invchi2(n,p)

chi2tail(n,x)=1-chi2(n,x)

invchi2tail(n,p)

ttail(n,t)

tden(n,t)

invttail(n,p)

F(n1,n2,f)

Fden(n1,n2,f)

invF(n1,n2,p)

Ftail(n1,n2,f)=1-F(n1,n2,f).

invnormal(p)

invFtail(n1,n2,p)

11.1
Binomial(n,k,p) p n
k 0.6
4 .54432
di Binomial(6,4,0.6)
.54432
4
di Binomial(6,4,0.6)- Binomial(6,5,0.6)
.27648

di Binomial(2,1,0.5)-Binomial(2,2,0.5)
0.5

di Binomial(2,1,0.5)
.75

di Binomial(2,2,0.5)
.25

di Binomial(2,0,0.5)
1

11.2
-1.96 0.025

chrisccb@126.com

115

STATA 11

.2

.4

.6

.8

di normal(-1.96)
.0249979
1.96 0.975
di normal(-1.96)
.9750021
1.96
di 1-normal(1.96)
.0249979

twoway function y=normal(x), rang(-4 4)

-4

-2

0
x

11.1p751-753
*============================begin=================================
mat z=J(61,11,.)
forvalues i=1/61{
mat z[`i',1]=(`i'-31 )/10
forvalues j=2/11 {
mat z[`i',`j']=normal((`i'-31)/10+(`j'-2)/100)
}
}
matrix colnames z = z 0 1 2 3 4 5 6 7 8 9
mat list z, format(%5.4f)
*============================end==================================

11.3
(x-m)/s=z
I.Q. 100 16
100-115
100-115
di normal((115-100)/16)- normal((100-100)/16)
.32574929

twoway function y=normal((x-100)/16), rang(50 150)



chrisccb@126.com

116

.2

.4

.6

.8

STATA 11

50

100
x

150

0.975
di invnormal(.975)
1.959964
1.96 normal(1.96)
. di invnormal(.995)
2.5758293
10%
72 13 10%

di invnormal(0.9)*13+72
88.66017

11.4
XFxY=F
X[01]P64

y=Fxx=invF(y).
YPY<=y=P(F(X)<=y)

Y[01],y<0p=0;y>1P=1,0<=y<=1
PF(x)<=y
=p{invF(F(x))<=invF(y))=p{x<=invF(y))=F(invF(y))=y


chrisccb@126.com

117

.2

.4

.6

.8

STATA 11

-4

-2

0
x

di invnorm(uniform())

*============================begin=================================
clear
set obs 10000
gen z=invnormal(uniform())
//
hist z,bin(100) norm
//
*============================end=======================

11.5
STATA
di normalden(1.95)
.05959471
s
normalden(z,s) = normalden(z)/s
di normalden(1.95,10)
.00595947
m, s
normalden(x,m,s) = normalden((x-m)/s)/s
di normalden(29.5,10,10)
.00595947

*============================begin=================================
#delimit ;
//
twoway
function y=normden(x), range(-4 4) || /**/
function y=2*normden(x-3), range(-4 7) || /* 3 2
*/
function y=2*normden(x), range(-4 4) clstyle(foreground) // 2
egend(off);

chrisccb@126.com

118

STATA 11

.2

y
.4

.6

.8

#delimit cr
*============================end=================================

-5

10

*============================begin=================================
#delimit ;
twoway
function y=normden(x), range(-4 -1.96) bcolor(gs12) recast(area) ||
function y=normden(x), range(1.96 4) bcolor(gs12) recast(area) ||
function y=normden(x), range(-4 4) clstyle(foreground) ||,
plotregion(style(none))
yscale(off) xscale(noline)
legend(off)
xlabel(-4 "-4 sd" -3 "-3 sd" -2 "-2 sd" -1 "-1 sd" 0 "mean"
1 "1 sd"
2 "2 sd"
3 "3 sd"
4 "4 sd", grid gmin gmax)
xtitle("");
#delimit cr
*============================end===============================

11.6

X Fx0<<1

F

chrisccb@126.com

119

STATA 11

P{X>F}=, 1-F F= F F=1-


X Fx

y
.2

.3

.4

.975

F=invF(1-)

.1

1.96

-1.96

1.96

*============================begin==============================
#delimit ;
twoway
function y=0.975, rang(-4 1.96) dropline(1.959)||
function y=normal(x), range(-4 4) clstyle(foreground) ||,
legend(off)
xlabel(1.96)
ylabel(.975)
;
#delimit cr
*============================end=============================
=0.05
di invnormal(0.95)
1.6448536
=0.05
di invnorm(0.975)
1.959964

11.7
X1X2Xn n Xi
X=Xi2 n
*============================begin============================
#delimit;
tw function y=(chi2(2,x)-chi2(2,(x-0.01)))/0.01,rang(0 30) ||
function y=(chi2(4,x)-chi2(4,(x-0.01)))/0.01,rang(0 30) ||
function y=(chi2(8,x)-chi2(8,(x-0.01)))/0.01,rang(0 30) ,legend(off);
tw function y=chi2(2,x),rang(0 30) ||

chrisccb@126.com

120

STATA 11

function y=chi2(4,x),rang(0 30) ||


function y=chi2(8,x),rang(0 30), legend(off);
***

.6

.003

.8

.004

.005

tw function y=100*(chi2(2,x)-chi2(2,(x-0.01))),rang(0 30) ||


function y=100*(nchi2(2,4,x)-nchi2(2,4,(x-0.01))),rang(0 30) ||
function y=100*(nchi2(2,8,x)-nchi2(2,8,(x-0.01))),rang(0 30) ,legend(off);
*============================end==============================

n=4

.2

.001

.4

.002

n=2

n=8

10

20

30

10

20

30

100.9510
18.310.95.
di invchi2(10,0.95)
18.307038
di chi2(10,18.31)
.95004583
chi2(n,x)=1- chi2tail(n,x)
di chi2tail(10,18.31)
.04995417
invchi2(n,p)=
invchi2tail(n,1-p)
di invchi2tail(10,0.05)
18.307038
11.2P758
*===========================begin================================
mat X=J(31,3,.)
forvalues n=1/30{
mat X[`n',1]=invchi2tail(`n',0.1)
mat X[`n',2]=invchi2tail(`n',0.05)
mat X[`n',3]=invchi2tail(`n',0.01)
}
mat list X, format(%5.2f)
*============================end================================


chrisccb@126.com

121

STATA 11

11.8 t
t n
8 t 0.05
di invttail(8,0.05)
1.859548

di ttail(8,1.86)
.04996531

t
di invttail(8,0.025)
2.3060041
di ttail(8,2.306)
.02500016
11.3 t (p754)
*===========================begin=================================
mat t=J(31,5,.)
forvalues n=1/30{
mat t[`n',1]=invttail(`n',0.1)
mat t[`n',2]=invttail(`n',0.05)
mat t[`n',3]=invttail(`n',0.025)
mat t[`n',4]=invttail(`n',0.01)
mat t[`n',5]=invttail(`n',0.005)
}
mat list t, format(%5.3f)
*===========================begin===============================

11.9 F
F
*===========================begin=================================
#delimit ;
twoway
function y=Fden(2,8,x), rang(0 4) ||
function y= Fden(6,8,x), rang(0 4) ||
function y= Fden(6,20,x), rang(0 4) legend(off);
*===========================begin=================================


chrisccb@126.com

122

STATA 11

.6

.8

df=2,8

6,8

.2

.4

6,20

2
x

X 10 5 F X 4.74
di F(10,5,4.74)
.95010421
di invF(10,5,0.95)
4.7350631
di Ftail(10,5,4.74)
.04989579
di invFtail(10,5,0.05)
4.7350631

X 5 10 F X
. di F(5,10,3.326)
.95000672
. di invF(5,10,0.95)
3.3258345
. di Ftail(5,10,3.326)
.04999328
. di invFtail(5,10,0.05)
3.3258345
F

F(n,m,f)=1-Ftail(n,m,f)

invF(n,m,p)=invFtail(n,m,1-p)

Ftail(m,n,a)= 1/ [Ftail(n,m,1a)]

di invFtail(5,10,0.05)
3.3258345
di 1/(invFtail(10,5,0.95))
3.3258345
11.4 F (p756)
*===========================begin=================================
mat F=J(21,11,.)
forvalues i=1/21{

chrisccb@126.com

123

STATA 11

mat F[`i',1]=`i'+9
forvalues j=2/11 {
mat F[`i',`j']=invFtail((`j'-1),(`i'+9),0.05)
}
}
matrix colnames z = F 1 2 3 4 5 6 7 8 9 10
mat list F, format(%4.2f)
*===========================end================================


chrisccb@126.com

124

STATA 12

12

12.1

.1

Density
.2

.3

.4

realinc 2

*============================begin=================================
use realinc, clear
hist inc, bin(200) norm /*bin(200) 200
norm */
g linc=ln(inc)
//
hist linc,bin(200) norm
//
sum linc,d
//
g f=exp(-(linc-9.35627)^2/(2*1.221415^2))/(sqrt(2*_pi)*1.221415) //
*g f=normden(linc, 9.35627, sqrt(1.221415))
line f linc,sort
//
tw hist linc || line f linc, sort //
linc,
bfcolor(none)
blcolor(none)
blwidth(none)
normal
hist
normopts( clcolor(red) clwidth(thick)) kdensity kdenopts( clcolor(green)
clwidth(thick) )
*===========================end====================================

10

12

14

linc


chrissccb@126.com

125

STATA 12

12.2

.05

Density

.1

.15

Nu,2 Nu,2/n

5 10 8
x1 8 x2
1000 1000

*============================begin=================================
capt prog drop sd
prog sd
drawnorm x,n(8) m(5) sds(10) clear //8 u=5,o=10
quietly sum x
end
*** 1000 1000
simulate sd m=r(mean), reps (1000)
drawnorm x, m(5) sds(10)
sum
//
tw (hist m, density blcolor(olive) ) (hist x, density bfcolor(green))
*============================end===================================

-40

-20

0
Density

20

40

Density

X
5
1/sqrt(8) 8

12.3


chrissccb@126.com

126

STATA 12

*============================begin================================
capt prog drop lnsd
prog lnsd
// lnsd
drop _all
rndexp `1 3
//, net get rnd
quietly sum xe
end
* 425100400 1000
foreach s of numlist 4 25 100 400 {
simulate m`s=r(mean), reps (1000) nodots: lnsd `s
save temp`s, replace
}
rndexp 1000 3
// DGP
merge using temp4 temp25 temp100 temp400
tw (hist xe, bfcolor(green) bin(100)) ///
(hist m4, blcolor(olive) bfcolor(none) bin(20)) ///
(hist m25, blcolor(gold) bfcolor(none) bin(20)) ///
(hist m100, blcolor(blue) bfcolor(none) bin(20)) ///
(hist m400, blcolor(red) bfcolor(none) bin(20)) , legend(off)

.1

Density

.2

.3

tw (kdensity xe) (kdensity m4) (kdensity m25) ///


(kdensity m100) (kdensity m400)
*============================end==================================

10
Exponential random num0

10

10

425
100 400


chrissccb@126.com

127

STATA 12

12.4

.001

.1

.002

.003

Density
.2

.3

.004

.4

.005

*============================begin=================================
drawnorm x1-x10,n(1000) clear // 10
forv i=1/10 {
replace x`i'=x`i'^2
// 10
}
forv i=1/10 {
egen y`i'=rsum(x1-x`i') // y1=x1, y2=x1+x2
}
tw (hist y2, blcolor(olive) ) (hist y4, bfcolor(green)) (hist y10, bfcolor(red))
tw function y=100*(chi2(2,x)-chi2(2,(x-0.01))),rang(0 30) || ///
function y=100*(chi2(4,x)-chi2(4,(x-0.01))),rang(0 30) || ///
function y=100*(chi2(10,x)-chi2(10,(x-0.01))),rang(0 30) legend(off)
*============================end==================================

10

20

30
0

y2/y4/y10
Density
Density

Density
0

10

20
x

n-1
X (x-u)/
n

n 1 2
S ~ 2 ( n 1)
( 2)
2

*============================begin=================================
capt prog drop s
prog s
drawnorm x,n(`1') m(5) sds(10) clear
quietly sum x
scalar s=(`1-1)*r(Var)/100 //var
end

chrissccb@126.com

128

30

STATA 12

.001

.1

.002

.2

Density

.003

.3

.004

.4

.005

.5

*35111000
foreach i of numlist 3 5 11 {
simulate var`i=s, reps (1000) nodots: s `i
save temp`i, replace
}
merge using temp3 temp5
tw (hist var3, bfcolor(olive)) (hist var5, bfcolor(green)) ///
(hist var11, blcolor(red) bfcolor(none))
*============================begin=================================

10

20
var

30

40

10

20
x

12.5 F
n m
F F

*============================begin=================================
drawnorm x1-x20,n(1000) clear
forv i=1/20 {
replace x`i'=x`i'^2
}
egen y8=rsum(x1-x8)
egen y20=rsum(x1-x20)
keep y8 y20
drawnorm x1-x10,n(1000)
forv i=1/10 {
replace x`i'=x`i'^2
}
egen z2=rsum(x1-x2)
egen z6=rsum(x1-x6)
keep y* z2 z6

chrissccb@126.com

129

30

STATA 12

.2

Density/y
.4
.6

.8

g f28=(z2/2)/(y8/8)
g f620=(z6/6)/(y20/20)
tw hist f28,bin(100) bfcolor(red) || hist f620,bin(30) blcolor(yellow) ||
function y=Fden(2,8,x), range(0 20) || function y=Fden(6,20,x), range(0 20)
*============================end==================================

10
f28/f620/x
Density
y

15

20

Density
y

12.6 t
t
n-1 t
T=

X
~ t ( n 1)
S/ n

(3)

*============================begin=================================
drawnorm x1-x20,n(1000) clear
forv i=1/20 {
replace x`i'=x`i'^2
}
forv i=1/20 {
egen y`i'=rsum(x1-x`i')
}
keep y1 y2 y4 y8 y20
drawnorm x,n(1000)
g t1=x/sqrt(y1)
g t2=x/sqrt(y2/2)
g t8=x/sqrt(y8/8)
g t20=x/sqrt(y20/20)
tw hist t2 ,bin(100) || hist t8 ,bin(100) || hist t20 ,bin(100)

chrissccb@126.com

130

STATA 12

.1

.1

y
.2

Density
.2

.3

.3

.4

.4

tw function y= tden(2,x),range(-4 4) || function y= tden(8,x),range(-4 4) ||


function y= tden(20,x),range(-4 4)
*============================end==================================

-5

0
t2/t8/t20
Density
Density

-4

-2

Density

0
x
y
y

12.7
*============================begin================================
clear
drawnorm x y, n(1000)
g z=exp(0.5*(-x^2-y^2))
scat3 x y z
// sct3 search scat3,net
scat3 x y z, msymbol(point) mcolor(gold) shadow(msize(0))
*============================end=================================
clear
drawnorm x y, n(10000)
g z=exp(0.5*(-x^2-y^2))
g y1=-x+invnormal(uniform())
g z1=exp(0.5*(-x^2-y1^2))
scat3 x y z, mcolor(gold) shadow(msize(0)) saving(1,replace)
scat3 x y1 z1, mcolor(gold) shadow(msize(0))saving(2,replace)
graph combine 1.gph 2.gph


chrissccb@126.com

131

STATA 12

clear
drawnorm x y, n(10000)
g z=exp(0.5*(-x^2-y^2))
g y1=x^3+invnormal(uniform())
g z1=exp(0.5*(-x^2-y1^2))
scat3 x y z, mcolor(gold) shadow(msize(0)) saving(1,replace)
scat3 x y1 z1, mcolor(gold) shadow(msize(0))saving(2,replace)
graph combine 1.gph 2.gph


chrissccb@126.com

132

STATA 13

13
13.1
10
012345678
9 1 10
10
10

*===========================begin==================================
capt prog drop mle
prog mle
/*101*/
drawnorm double x0-x9,n(8) m(0,1,2,3,4,5,6,7,8,9) clear
global i=int(10*uniform())
//
forv j=0/9 {
gen lnf`j' =-0.5*ln(2*_pi)*8-sum(0.5*(x$i-`j')^2) //
scalar lnf`j'=lnf`j'[_N]
//
}
scalar list
// 10
end
mle
*10
di "" as error "X"$i //
*===========================end====================================

STATA
stata

13.2
*===========================begin==================================
capt prog drop bb
prog bb //
args lnf u v //,u v
quietly replace `lnf' = -0.5*ln(2*_pi) - ln(`v') -0.5*($ML_y1-`u')^2/(`v')^2
end
drawnorm x,n(100) m(10) sd(3) clear//103100
ml model lf bb (x=) (variance:) //

chrisccb@126.com

133

STATA 13

ml maximize //
*===========================end====================================
argslnfu
v
quietly replace, replace
`lnf
`lnf[_N] $ML_y1
stata
ml model stata bb

ml maximiz

13.3 OLS

10
0123456789 1
10
10

*===========================begin================================
capt prog drop ols
prog ols
drawnorm double x0-x9,n(8) m(0,1,2,3,4,5,6,7,8,9) clear
*10,
global i=int(10*uniform())
//0129
forv j=0/9 {
gen lnf`j' =sum((x$i-`j')^2) //10
scalar lnf`j'=lnf`j'[_N]
//
}
scalar list
//10
end
ols
*10
di "" as error X $i //?
*===========================end====================================


chrisccb@126.com

134

STATA 13

13.4 MM

10 01234
56789 8

*===========================begin=================================
cap prog drop mm
drawnorm double x0-x9,n(8) m(0,1,2,3,4,5,6,7,8,9) clear
*10,10
//0129
global i=int(10*uniform())
quietly sum x$i
di r(mean)
*
di "" as error X $i " //?
*===========================end====================================

13.5

*============================begin=================================
capt prog drop bb
prog bb
drawnorm x,n(100) m(5) sds(10) d clear
/*u=5,o=10100*/
quietly sum x
end
***100100meansd
simulate mean=r(mean) sd=r(sd), reps (100) nodots: bb
g n=_n
*1010095%
g zlow=mean-invnorm(0.975)*10/sqrt(100)
g zhigh=mean+invnorm(0.975)*10/sqrt(100)
*sdt
g tlow=mean-invttail(99,0.025)*sd/sqrt(100)
g thigh=mean+invttail(99,0.025)*sd/sqrt(100)
*95%1
g zsign=(zlow<5& zhigh>5)

chrisccb@126.com

135

STATA 13

thigh/tlow
4
6

10

g tsign=(tlow<5& thigh>5)
*95%
table zsign
table tsign
*
tw rcapsym thigh tlow n, yline(5) || rcapsym thigh tlow n if thigh<5 | tlow>5
*============================end===================================

20

40

60

80

100

n
thigh/tlow

thigh/tlow

13.6
12

95%
95% 5%

(n-1) t
1 u=5
u0=5
*============================begin================================
drawnorm x,n(100) m(5) sds(10) d clear
*u=5,o=10
quietly sum x
di as text "t" as error (r(mean)-5)/(sqrt(100)*r(sd))
di as text "t" as error invttail(99,0.025)
di as result ""

chrisccb@126.com

136

STATA 13

*===========================end===================================

1005
100
*===========================begin=================================
capt prog drop bb
prog bb
drawnorm x,n(100) m(5) sds(10) d clear
quietly sum x
scalar ref=(abs(sqrt(100)*(r(mean)-5)/r(sd))>invttail(99,0.025))
*tjud=1,0
end
simulate ref,reps(100):bb
tab _sim
//1100
*===========================begin=================================
2 u=5
u0=10
*===========================begin=================================
capt prog drop bb
prog bb
drawnorm x,n(100) m(5) sds(10) d clear
quietly sum x
scalar ref=(abs(sqrt(100)*(r(mean)-10)/r(sd))>invttail(99,0.025) )
end
simulate jud,reps(100):bb
tab _sim
*===========================begin=================================
100 10


chrisccb@126.com

137

STATA

14

14.1

XYY=f(X)

v
d

v2
d = sin 2
g

didi1
^di
i
2

v
d i = i sin 2 i + ui
gi
Vg,

v
di =
sin 2
g
Vgui

v2
d i = di + ui = sin 2 + ui
g
uidi


chrisccb@126.com

138

STATA

,
,.

v00div00
fd|v0,0
vk,
2

vk
sin 2 0 + u j
g

( k = 1,2,...m)

dj =

.3

(i = 1,2,...n)

y
.2

v0
sin 2 0 + ui
g

.1

di =

.4

v0,0n
uif(u|v=v0

50

100
x

150

dv
v0
02u0v=v0
du0
,0

E ( d | v = v0 ) =

v0
sin 2 + u0
g

var( d | v = v0 ) = var(

v0
sin 2 + u | v = v0 ) = var(u | v = v0 ) = 02
g

E ( d | v = vk ) =

vk
sin 2 + uk
g

var( d | v = vk ) = var(

v0
sin 2 + u | v = vk ) = var(u | v = vk ) = k2
g

45100u0=4, 0=0.09
2

v
10000
E ( d | v = 1) = 0 sin 2 + u0 =
+4
g
9.8
var( d | v = 1) = 02 = 0.09
,
N10000/9.8+4, 0.09,
95%


chrisccb@126.com

139

STATA

d = g (v ) =

v2
sin 2
g

d = g (v ) = ?
6.00

g(v)g(vk)

mean(y)

4.00

d = g (v ) = 0 + 1v + 2 v 2 + ... + (v )

2.00

d = g (v) = 0 + 1v + (v )
vki

0.00

d i = 0 + 1vk + (vk ) + ui

10

vk

E ( d | vk ) = E ( 0 + 1vk + o(vk ) + ui | vk ) = 0 + 1vk + o(vk ) + uk

f(u|vk)ukvkukvk
vkf(u|vk)2
01
o(vk)=00=^01=^1,
g(x) d = g ( v ) =

0 + 1v = 0 + 1v

0=^01=^1
vkvk=5/Ed|vk=200
E ( d | vk ) = 0 + 1vk + uk

200 = 0 + 51 + uk

(3)

v01
vm=8/Ed|vm=300,
300 = 0 + 81 + um
(4)
43

100 = 31 + um uk

uk=2um=31=[100-3-1]/3=33
5
1uk=um,
ukum,5

100 = 31

ukumEu|vk=E(u|vm)
6
E (u | v ) = u
678
*
u
*


chrisccb@126.com

140

STATA

E (u ) = E[ E (u | v)] = u *
~ = E (u u * ) = u * u * = 0
Eu
7
~
~
~
~
cov(v, u ) = cov(v, u ) = E[(v Ev )(u Eu )] = Eu v = 0

d i = 0 + 1vk + ui

d i = ( 0 + u * ) + 1v k + ui u * = 0* + 1v k + u~i
E ( d | vk ) = 0* + 1vk + E (u~i | vk ) = 0* + 1vk

v
vk9
*
*
0 0u
9
SLR1
SLR2
SLR3

2
(10x=1-10)10000bomb
xyE(d|v),
v
1
2
3
4
5
6
7
8
9
10
Ed|v) .13
.47
.76
.58
1.15
2.53
2.61
3.44
4.43
5.35

E ( d | v = 1) = 0* + 1 1 = 0.13
E ( d | v = 2) = 0* + 1 2 = 0.47
...
E ( d | v = 10) = 0* + 1 10 = 5.35

nEd|v
d
d

n1

E ( d | v = 1) = E ( d | v = 1) + 1 = n11 d i + 1 = 0.13 + 1
i =1

E ( d | v = 1) = 0* + 1 1 = d1 + = 0.13 + 11

0* + 1 vk = d k + k
2

clear
set obs 10000
gen x=int((_n-0.5)/1000)+1
gen u=9*invnorm(uniform())
gen y=x^2/9.8*sin(_pi/6)+u
table x, c(mean y) format(%5.2f)

chrisccb@126.com

141

STATA

0* + 1 v = d +

1 (vk v ) = ( d k d ) + ( k )

d i = 0 + 1vi + ui = 0* + 1vi + u~i


78
Eu~ = 0
7
~
Eu v = 0
8

SLR4
78

Eu~ = E ( d i 0* 1vi ) = 0
Eu~v = E[u~( d * v )] = 0
i

1 i

1 n
E u~ = ( d i 0* 1vi ) = 0
n i =1
1 n
E (u~v ) = vi ( d i 0* 1vi ) = 0
n i =1

(v v )(d d )
(v v )
i

P46

14.2

45110
0.09

di =

vi2
1 2
sin 2 + ui =
vi + ui = 0.102vi2 + ui
g
9.8

ui ~ N (0,0.09)

*********************
*===========================begin====================================
capt prog drop bomb
prog bomb
scalar x=1+int(10*uniform())
//110
scalar y=x^2/9.8*sin(_pi/2)+0.09*invnorm(uniform()) //
end
clear

chrisccb@126.com

142

STATA

simulate "bomb" x=x y=y,reps(30)


reg y x
di 1/9.8*sin(_pi/2)

//3030

// y=a+bx+u
//95%

gen x2=x^2
// y=a+bx2+u
reg y x2
//
di 1/9.8*sin(_pi/2)
//95%
*===========================end====================================
X

0.10295

*===========================end====================================
clear
mat m=(3,4,5,0)
mat sd=(9,9.6,0.01,0\9.6,16,12,0\0.01,12,25,0\0,0,0,1)
/*,X1()X2(),X3(),
,*/
capt prog drop bb
prog bb
drop _all
drawnorm x1 x2 x3 x4,n(30) means(m) cov(sd)
gen y=120+50*x1+100*x2+30*x3+x4
quietly reg y x1 x2 x3
end
simulate _b _se,reps(1000): bb
hist _b_x1

14.3

var( d | v = vk ) = var(

v0
sin 2 0 + u | v = vk ) = var(u | v = vk ) = k2
g

SLR5

var( d | v ) = var(u | v ) = k2 = 2
p662

var( d | v ) = var(u | v ) = E (u 2 | v ) [ E (u | v )]2 = 2

E (u 2 | v ) = 2

E (u 2 | v ) = E[( d i 0 1vk ) 2 | v ] = 2

chrisccb@126.com

143

STATA

uvp662

E (u 2 ) = E (u 2 | v ) = 2

ui = d i 0 1vi = 0 1vi + ui 0 1vi = ui ( 0 0 ) ( 1 1 )vi

0 = ui ( 0 0 ) ( 1 1 )vi

ui = ui ui ( 1 1 )(vi vi )
dyvx,

(1) u i = yi 0 1 xi
= ( 0 + 1 xi + ui ) 0 1 xi
= u ( ) ( ) x
i

( 2) u i = u ( 0 0 ) ( 1 1 ) x
(3) u = (u u ) ( )( x x )
i

( 4) u i = (ui u ) + ( 1 1 ) 2 ( xi x ) 2 2( 1 1 )(ui u )( xi x )
2
(5) u i = (ui u ) 2 + ( 1 1 ) 2 ( xi x ) 2 2( 1 1 ) ui ( xi x )
2

2
(6) E ( u i ) = E[(ui u ) 2 ] + E[( 1 1 ) 2 ] ( xi x ) 2 2 E[( 1 1 ) ui ( xi x )]

= ( n 1) 2 + 2 2 2 = ( n 2) 2
( 7) E (

1
1
2
2
u i ) = 2 , 2 =
u i 2

n2
n2

regressregress
*===========================begin====================================
capt prog drop bomb
prog bomb
scalar x=1+int(10*uniform())
scalar y=x^2/9.8*sin(_pi/2)+0.09*invnorm(uniform())
end
clear
simulate "bomb" x=x y=y,reps(30)
//
gen x2=x^2
// y=a+bx2+u
* 1 =

( x x )( y y )
(x x)
i

*b1
egen my=mean(y)
//y
egen mx=mean(x2)
//x2
gen nmy=y-my
//y
gen nmx=x2-mx
//x2
egen fz=sum(nmx*nmy)
//
egen fm=sum(nmx^2)
//
egen sst=sum(nmy^2)

chrisccb@126.com

144

STATA

scalar b1=fz[_N]/fm[_N]
scalar b0=my[_N]-b1*mx[_N]
* =
2

1
2
ui
n2

//b1
//b0

2 ,

gen uh=y-b0-b1*x2
//
gen uh2=uh^2
sum uh2
scalar SSR=r(sum)
//SSR
scalar SST=sst[_N]
// SST
scalar SSE=SST-SSR
// SSE
scalar R2=SSE/SST
//R2
scalar F= SSE/(SSR /(_N-2))
//F
scalar PF=Ftail(1,_N-2,F)
//FP
scalar SER=sqrt(SSR/(_N-2))
//^

( )

* Var 1 = 2 =
sx

(x
i =1

x)

b1
2

sum x2
scalar SX2= r(Var)* (_N-1)
scalar seb1= SER/sqrt(SX2)

//Sx2
//b1

scalar tb1= b1/seb1


scalar pb1=ttail(_N-2,tb1)
scalar condn=b1-invttail(_N-2,0.025)*seb1
scalar conup=b1+invttail(_N-2,0.025)*seb1

//b1t
//b1p
//95%
//95%

reg y x2
//
ereturn list
//
di e(rss)
// SSRe(rss)
di e(rss)/(_N-2)
//
di e(rmse)
//
sum x2
di _b[x2]/e(rmse)/sqrt (r(Var)*(_N-1)) //b1t
di ttail((_N-2), _b[x2]/e(rmse)/sqrt(r(Var)* (_N-1))) //p
di _b[x2]+invttail((_N-2),0.025)*e(rmse)/sqrt(r(Var)* (_N-1)) //95%
di e(mss)/(e(rss)/(_N-2))
//F
di Ftail(1,28,e(mss)/(e(rss)/(_N-2)))
//FP
*===========================end====================================

14.3
e ~ N (0, 2 )
y = 0 + 1 x + e ~ N ( 0 + 1 x, 2 )
e y


chrisccb@126.com

145

STATA

0 + 1 x x
01

*===========================begin==================================
capt prog drop bb
prog bb
args lnf theta1 theta2
quietly replace `lnf' = ///
-0.5*ln(2*_pi)-ln(`theta2')-0.5*($ML_y1-`theta1')^2/(`theta2')^2
end
drawnorm x u,n(30) clear
gen y=10+8*x+invnorm(uniform())
ml model lf bb (y= x) (variance:)
ml maximize
*===========================end===================================


chrisccb@126.com

146

STATA

15

15.1

y=x+e, e~N(0,2)y~ N(x,2)


Ey|x=x
clear
set obs 1000
gen x=int(5*uniform())+1
//x15
gen y=x+invnorm(uniform())
//yx+e
gen f=normden(y,x,1)
//y
scat3 y x f
//,scat3

y=x+e, eN(0,i2)y N(x,i2)


Ey|x=xvar(y|xi)= i2
clear
set obs 1000
gen x=int(5*uniform())+1
gen y=.
gen f=.
forvalue i=1/5 {
drawnorm e`i',n(1000) m(0) sds(`i')
//15
replace y=x+e`i' if x==`i'
replace f=normden(y,x,`i') if x==`i'
}
scat3 y x f


chrisccb@126.com

147

STATA

15.2
ux
MRL.5: Var(u|x1,,xk)=2
(heteroskedasticity): Var(ui|xi1,,xik) =i2

OLS

2
SST

x
(1) OLS
,.
,,
.

(2)OLS
(xi x ) i2

=
ROLS
,?
SSTx2
! var(GLS)<=var(ROLS)
, t F
,.

(3)GLS BLUE
GLS OLS
GLS WLS WLS GLS


chrisccb@126.com

148

STATA

yi = 0 + 1 xi + ui
yi

= 0

+ 1

xi

E (ui2 ) = i2
+

ui

i2
var( ) = E ( ) = 2 E (u ) = 2 = 1
i
i
i
i
ui

min (

ui

ui

) 2 = min (

2
i

yi

= min ( yi 0 1 xi ) 2

xi

)2

i2

y=5+8*x+ui
ui~N(0,xia), a=0,a=1,a=2,a=3,a=4 ,
OLS, OLS GLS ,.
*===========================begin====================================
clear
capt prog drop het
prog het
drop _all
set obs 100
gen x=uniform()
gen u=sqrt(x^`1')*invnorm(uniform())
//ui~N(0,xia),
gen y=5+8*x+u
end
forvalue i=0/4 {
//a=0,a=1,a=2,a=3,a=4
quietly {
4
het `i' //i=0ui~N(0,1)i=4ui~N(0,xi )
reg y x
//OLS
esti store ols`i' //ols`I
reg y x , robust
//
esti store rols`i'
gen w`i'=1/(x^`i')
//
reg y x [aw=w`i']
//WLS
esti store wls`i'
replace y=y/sqrt(x^`i')
//y*=y/
gen x0=1/sqrt(x^`i')
replace x=x/sqrt(x^`i') //x*=y/
*
reg y x0 x,noc
// GLS,y*=ax0+bx 1+u,noc
esti stor gls`i
}
esti table ols`i' rols`i' gls`i' wls`i,se //
}
*===========================end====================================


chrisccb@126.com

149

STATA

:,OLS ()GLS
, a .
GLS

15.3

yi = 0 + 1 xi + ei
ei ~ N (0, i2 )
(i) i2 =
(ii) i2 = xi2
(ii) i2 = xi
iiiiii

*===========================begin====================================
clear
set obs 1000
gen x=uniform()
gen u1=invnorm(uniform()) //
2
gen u2=x^2*invnorm(uniform()) //u2i~N(0,xi )
gen u3=x*invnorm(uniform())
//u3i~N(0,xi)
gen y1=1+5*x+u1
gen y2=1+5*x+u2
gen y3=1+5*x+u3
reg y1 x
rvpplot x
//,YY^YX
imtest,white //
reg y2 x
rvpplot x
//YxX
imtest,white
//
reg y3 x
rvpplot x
imtest,white
*===========================end====================================


chrisccb@126.com

150

STATA

yi = 0 + i xi1 + 2 xi 2 + ei
ei ~ N (0, i2 )

i2 = e + ln( x ) + ln( x
(i) 1 = 2 = 0
(ii) 1 = 2, 2 = 0
(iii) 1 = 0, 2 = 2
(iv) 1 = 2 = 1
0

i1

i2

iii-iv

*===========================begin====================================
clear
set obs 1000
gen x1=uniform()
gen x2=1+3*invnorm(uniform())
gen e=invnorm(uniform()) //
gen u2=exp(2*ln(x1))*e
//a1=2,a2=0,x1
gen u3=exp(2*ln(x2))*e
//a1=0,a2=2,x2
gen u4=exp(ln(x1)+ln(x2))*e //a1=1,a2=1,x1x2
gen y1=1+3*x1+5*x2+e
gen y2=1+3*x1+5*x2+u2
gen y3=1+3*x1+5*x2+u3
gen y4=1+3*x1+5*x2+u4
reg y1 x1 x2
rvfplot
reg y2 x1 x2
rvpplot x1
reg y3 x1 x2
rvpplot x2
reg y4 x1 x2
rvfplot
imtest,white
*===========================begin====================================

15.4 ()


chrisccb@126.com

151

STATA

y i = 0 + 1 x i + ei
ei ~ N (0, i2 )
(i ) i2 = i
(ii) i2 = i x i2
(ii) i2 = i x i
n=10,20,30,40,50,60,70,805%10%white
1000

*===========================begin====================================
clear
set more off
capt prog drop het
prog het
quietly {
drop _all
set obs `1' //`1
gen x=uniform()
gen u1=invnorm(uniform())
//
2
gen u2=x^2*invnorm(uniform()) //u2i~N(0,xi )
gen u3=x*invnorm(uniform())
//u2i~N(0,xi)
gen y1=1+5*x+u1
gen y2=1+5*x+u2
gen y3=1+5*x+u3
reg y1 x
imtest,white
//
scalar z1=r(p)
//Pz1
reg y2 x
imtest,white
scalar z2=r(p)
reg y3 x
imtest,white
scalar z3=r(p)
}
end
forvalues i=10(10)80 { //1020.7080
simulate z1 z2 z3,rep(100) nodots:het `i'
mkmat _s*, mat(A) //PA
mat B=(nullmat(B),A) //PB
}
svmat B
//B
drop _sim*
quietly forvalue i=1/24 {
gen a`i'=(B`i'>0.05)
//P0.0510


chrisccb@126.com

152

STATA

}
sum a*,seps(3)
*
mata
A=st_matrix("B")
A=A:>0.05
(mean(A))'
end
*===========================end====================================

100

yi = 0 + i xi1 + 2 xi 2 + ei

ei ~ N (0, i2 )

i2 = e + ln( x ) + ln( x
(i) 1 = 2 = 0
(ii) 1 = 2, 2 = 0
(iii) 1 = 0, 2 = 2
(iv) 1 = 2 = 1
0

i1

i2

*===========================begin====================================
clear
set memory 40m
set matsize 2000
capture program drop het
program het
quietly {
drop _all
set obs `1'
gen x1=uniform()
gen x2=1+3*invnorm(uniform())
gen e=invnorm(uniform())
gen u2=exp(2*ln(x1))*e
gen u3=exp(2*ln(x2))*e
gen u4=exp(ln(x1)+ln(x2))*e
gen y1=1+3*x1+5*x2+e
gen y2=1+3*x1+5*x2+u2
gen y3=1+3*x1+5*x2+u3
gen y4=1+3*x1+5*x2+u4
forvalues i=1/4 {
reg y`i' x1 x2
imtest,white
scalar z`i'=r(p)
}

chrisccb@126.com

153

STATA

}
end
forvalues i=10(10)80 {
simulate "het `i'" z1 z2 z3 z4,rep(1000)
mkmat _s*, mat(A)
mat B=(nullmat(B),A)
}
svmat B
drop _sim*
quietly forvalue i=1/32 {
gen a`i'=(B`i'>0.05)
}
sum a*, sep(4)
*===========================begin====================================

15.5 WLS GLS

WLS

FGLS

White

yi = 10+ 5xi +ui


ui ~ N(0; i)
=======================begin===================================
clear
capt prog drop het
prog het
drop _all
set obs 100
gen x = invnorm(uniform())
gen z = _n
gen e = sqrt(z)*invnorm(uniform())
gen y = 10 + 5*x + e
quietly reg y x
end
=======================end===================================
OLS
het
reg y x
x1000

simulate _be _se,reps(1000):het


x


chrisccb@126.com

154

STATA

OLS
WLS
:
=======================begin===================================
clear
capt prog drop het
prog het
drop _all
set obs 100
gen x = invnorm(uniform())
gen z = _n
gen e = sqrt(z)*invnorm(uniform())
gen y = 10 + 5*x + e
reg y x [aweight=1/z]
end
=======================end===================================
R21000
simulate _be _se,reps(1000) :het
,OLS
WLSOLS:
=======================begin===================================
clear
capt prog drop het
prog het
drop _all
set obs 100
gen x = invnorm(uniform())
gen z = _n
gen e = sqrt(z)*invnorm(uniform())
gen y = 10 + 5*x + e
reg y x [aweight=1/x ]
end
=======================end===================================
WLS 1000
simulate _be _se,reps(1000): het
WLS WLS

15.6 FGLS

(1) OLSi
(2) ln(i2)
(3) ln(2) i
(4) i = exp(i)
(5) 1/ i ,WLS


chrisccb@126.com

155

STATA

yi = 0 + i xi1 + 2 xi 2 + ei
ei ~ N (0, i2 )

i2 = e + ln( x ) + ln( x
(i) 1 = 2 = 0
(ii) 1 = 2, 2 = 0
(iii) 1 = 0, 2 = 2
(iv) 1 = 2 = 1
0

i1

i2

clear
set obs 100
gen x1=uniform()
gen x2=1+3*invnorm(uniform())
gen e=invnorm(uniform())
gen u2=exp(2*ln(x1))*e
gen u3=exp(2*ln(x2))*e
gen u4=exp(ln(x1)+ln(x2))*e
gen y1=1+3*x1+5*x2+e
gen y2=1+3*x1+5*x2+u2
gen y3=1+3*x1+5*x2+u3
gen y4=1+3*x1+5*x2+u4
*GLS
reg y1 x1 x2
reg y2 x1 x2 [aw=1/x1]
reg y3 x1 x2 [aw=1/x2]
gen x12=x1*x2
reg y4 x1 x2 [aw=1/x12]
*FGLS
forvalues i=1/4 {
reg y`i x1 x2
predict uh`i,res
gen luh`i=ln(uh`i*uh`i)
reg luh`i x1 x2
predict g`i
gen `i=exp(`i)
reg y2 x1 x2 [aweight=1/`i]
}


chrisccb@126.com

156

STATA 16

16
16.1
STATA 1960 0 1960 1 2 1
help dates
----- Numerical value & interpretation -----Format
Meaning
Value=-1
%tc
clock
31dec1959
23:59:59.999
00:00:00.000
00:00:00.001
%td
days
31dec1959
%tw
weeks
1959w52
%tm
months
1959m12
%tq
quarters
1959q4
%th
half years
1959h2
%tg
generic
-1

Value=0
01jan1960

Value=1
01jan1960

01jan1960
1960w1
1960m1
1960q1
1960h1
0

02jan1960
1960w2
1960m2
1960q2
1960h2
1

*
di (mdy(10,26,2007)-mdy(3,27,1979))/365.25
*
sysuse sp500, clear
gen d=day(date)
gen w=week(date)
gen m=month(date)
gen q= quarter(date)
gen hy= halfyear(date)
gen y=year(date)
gen ndate1=mdy(m,d,y)
gen weekd=dow(date)
//
//
gen yeard=doy(date)
*
tsset date
list if tin(08jan2001 ,23jan2001) //1823
list if tin( ,08jan2001)
*
use http://fmwww.bc.edu/ec-p/data/wooldridge/nyse, clear
save nyse, replace
tsset t
//
g r_1=return[_n-1]
//
g r1=L.return
//
g r4=L4.return //
list r* in 1/10
g f2=F2.return
//

chrisccb@126.com

157

STATA 16

g d1=D.return
//
g s1=S.return
//
list return f* d* d s in 1/10
reg return L.return L2.return S.price D(1/3).price //\
g price1=(price[_n-1]+price[_n]+price[_n+1])/3 //,3
//
egen price2=ma(price),nomiss t(3)
egen price31=ma(price), t(31)
//
tsline price price1 price31
tsline price price31 in 200/400
smooth 31 price, gen(price31r)
//
list price31* in 100/110
tsline price price31r in 200/400
gen rough=price-price31
//
tsline price rough

16.2
m, t1 , t 2 , ", t m T
Ft1 ,t2 "tm ( x1 , x2 , ", xm ) = Ft1+ ,t2+ "tm+ ( x1 , x2 , " , xm )

1) EX t2 < , t T
2) EX t = , t T
3) (t , s ) = (k , k + s t )t , s, kk + s t T

(1) EX t = , t T

2 , t = s
(2) (t , s ) =
, t , s T
0, t s

BLUE


chrisccb@126.com

158

STATA 16

Barlett : n

k ~ N (0, )
,k 0
n
m

H 01 = 2 = " = m = 0, m 1

H1 k 0, m 1k m
m

Q = n k2 ~ 2 (m)

LB

LB = n(n + 2) (

k =1

k =1

k2
nk

) ~ 2 ( m)

ARMAsim_arma 3,
set seed 1234
drawnorm x, n(691) sds(3) clear
set seed 1234
sim_arma y, sigma(3) //xy
tsline y //
hist y ,bin(50) norm //
sum y, d //
ttest y==0 //
sdtest y==1 //1
pnorm y, grid
//
wntestb y
//
wntestq y
//
corrgram y //Q
ac y
//
pac y
//
nyse.dta ,,
? ?
use nyse, clear
tsset t
3

Search sim_arma,net click here to install



chrisccb@126.com

159

STATA 16

rename return y
tsline y
//
hist y, bin(50) norm //
sum y, d //
ttest y==0 //
sdtest y==1 //1
pnorm y, grid
//
//
swilk y
sktest y
//
wntestb y
//
wntestq y
//
corrgram y //Q
ac y
//
pac y
//
reg y L.y

16.3 AR
p AR(p)

xt = 0 + 1 xt 1 + 2 xt 2 + " + p xt p + t

p 0

2
E ( t ) = 0Var ( t ) = , E ( t s ) = 0, s t
Ex = 0, s < t
s t

0 = 0 AR(p)
clear
set seed 1234
sim_arma y, ar(0.8) n(100)
set seed 1234
g x=y in 1
quietly forvalues i=2/100 {
replace x=0.8*x[_n-1]+invnormal(uniform()) in `i'
}
y x

(1) xt = 0.8 xt 1 + t
(2) xt = 1.1xt 1 + t
(3) xt = xt 1 0.5 xt 2 + t

chrisccb@126.com

160

STATA 16

-2

AR(0.8)

50

100

-4

-2

AR(1,-0.5)

50

AR(-1,1)

0 5.00e+283
1.00e+284
1.50e+284

-40000
-20000 0 2000040000

(4) xt = xt 1 + 0.5 xt 2 + t
clear
sim_arma x1, nobs(100) ar(.8)
sim_arma x2, ar(-1.1)
sim_arma x3, ar(1, -0.5)
sim_arma x4, ar(1, 0.5) spin(2000)
reshape long x, i(_t) j(n)
label define nlb 1 "AR(0.8)" 2 "AR(-1,1)" 3 "AR(1,-0.5)" 4 "AR(1,0.5)"
label value n nlb
tsline x, by(n, rescale)

100

50

100

AR(1,0.5)

50

100

_t
Graphs by n

AR

AR(p)p

clear
sim_arma x1, nobs(100) ar(.8)
sim_arma x4, ar(1, 0.5) spin(2000)
kpss x1,notrend
kpss x4,notrend
AR
AR(p) Ext = E (0 + 1 xt 1 + " + p xt p + t )
{ t }

Ext = , E ( t ) = 0 , t T

chrisccb@126.com

1 1 " p
161

STATA 16

AR(p)

xt k
E ( xt xt k ) = 1 E ( xt 1 xt k ) + " + p E ( xt p xt k ) + E ( t xt k )

E ( t xt k ) = 0

k = 1 k 1 + 2 k 2 + " + p k p

k
k = k = 1 k 1 + 2 k 2 + " + p k p
0
p

AR (k ) = ci ik
p

k
(k ) = ci i 0

i =1

c1 , c2 ," , c p

i =1

AR(1)
AR(1)

AR(1)

2
k = 1 k 1 = 0 =
, k 1
1 12
k
1

k
1

k = 1k , k 0

AR(2)
1 2

2
0 = (1 + )(1 )(1 + )
2
1
2
1
2

1 0

1 =
1 2

k = 1 k 1 + 2 k 2k 2

clear
sim_arma x1, nobs(100) ar(.8)
sim_arma x2, ar(-1.1)
sim_arma x3, ar(1, -0.5)
sim_arma x4, ar(1, 0.5) spin(2000)

1,


k = 1
1 2
1 k 1 + 2 k 2

ac x1,lags(20) title("ACF for AR(1) p= 0.8") ytitle("")


ylabel(,format(%3.1f)) note("") saving(1,replace)
ac x2,lags(20) note("") title("ACF for AR(1) p=-0.8")
ytitle("") ylabel(,format(%3.1f)) saving(2,replace)
ac x3,lags(20) note("") title("ACF for AR(1) p1=1 p2=-0.5")
ytitle("") ylabel(,format(%3.1f)) saving(3,replace)
ac x4,lags(20) note("") title("ACF for AR(1) p1=-1 p2=-0.5")
ytitle("") ylabel(,format(%3.1f)) saving(4,replace)
graph combine 1.gph 2.gph 3.gph 4.gph,ycom


chrisccb@126.com

k =0
k =1
k2

///
///
///
///

162

STATA 16

PACF for AR(1) p= 0.8

15

10
Lag

15

20

1.0
0.5
10
Lag

15

20

0.0
-1.0 -0.5

10
Lag

15

20

10
Lag

15

20

PACF for AR(1) p1=-1 p2=-0.5

0.5

1.0
0.5
-1.0 -0.5
5

PACF for AR(1) p1=1 p2=-0.5

0.0

0.5
0.0
-1.0 -0.5
0

20

1.0

10
Lag

ACF for AR(1) p1=-1 p2=-0.5

1.0

ACF for AR(1) p1=1 p2=-0.5

0.5

0.0

20

-1.0 -0.5

15

1.0

10
Lag

-1.0 -0.5

0.0
-1.0 -0.5

-1.0 -0.5
5

0.0

0.5

1.0
0.5
0.0

0.5
0.0
-1.0 -0.5
0

PACF for AR(1) p=-0.8

1.0

ACF for AR(1) p=-0.8

1.0

ACF for AR(1) p= 0.8

10
Lag

15

20

10
Lag

15

20

AR(p) k k-1
k-1 xt k xt
)( x Ex
)]

E[( xt Ex
t
t k
t k
xt , xtk xt1 ,", xtk +1 =
2

E[( xt k Ext k )
k k k
1 = k 1 0 + k 2 1 + " + kk k 1
= + +"+
2
k1 1
k2 0
kk k 2

""""""""

k = k1 k 1 + k 2 k 2 + " + kk 0

AR(p) P

kk =

)( x Ex
)]
E[( xt Ex
t
t k
kt
2

E[( xt k Ext k ) ]

kk = 0 , k > p

16.4 MA

q MA(q) = 0
MA(q) xt = + t 1 t 1 2 t 2 " q t q

q 0

2
E ( t ) = 0Var ( t ) = , E ( t s ) = 0, s t
MA

+ t 1 t 1 2 t 2 " q t q=
Ext = E
Var ( xt ) = Var ( + t 1 t 1 2 t 2 " q t q ) = (1 + 12 + " + q2 ) 2
p
k =0
1,
(1 + 12 + " + q2 ) 2 , k = 0

qk

k + i k + i
qk

i =1
kq
k = ( k + i k +i ) 2 , 1
, 1 k q
k =

2
2
1
i
=

chrisccb@126.com 1 + 1 + " + q
0,
k >q
0,
k>q

163

STATA 16

MA(1) MA(2)
1

1
k =
2
1 + 1
0

,k = 0
,k =1
,k 2

,k = 0

1
+
1 2 1 22
1 + 1 + 2
k =
2
1 + 12 + 22

,k = 1
,k = 2
,k 3

kk = (1 t 1 " q t q )(1 t k 1 " q t k q +1 )

1 ," q kk

(1) xt = t 2 t 1
(2) xt = t 0.5 t 1

4
16
(3) xt = t t 1 + t 2
5
25
5
25
(4) xt = t t 1 + t 2
4
16
MA MA

(1) xt = t 2 t 1 (2) xt = t 0.5 t 1


4
16
5
25
(3) xt = t t 1 + t 2 (4) xt = t t 1 + t 2
5
25
4
16

MA MA AR
MA MA
MA

MA(q)MA(q)i < 1

clear
sim_arma x1, nobs(100) ma(-2)
sim_arma x2, ma(-0.5)
sim_arma x3, ma(-0.8, 0.64)
sim_arma x4, ma(-1.25, 0.64)
pac x1, saving(1,replace)
pac x2, saving(2,replace)
pac x3, saving(3,replace)
pac x4, saving(4,replace)
graph combine 1.gph 2.gph 3.gph 4.gph,ycom


chrisccb@126.com

>1

164

STATA 16

ACF for MA(1) p=-0.5

10
Lag

15

20

10
Lag

15

20

10
Lag

15

20

ACF for MA(2) p1=-1.25 p2=0.64

10
Lag

15

20

10
Lag

15

PACF for MA(2) p1=-0.8 p2=0.64


-0.8 -0.6 -0.4 -0.2 0.0 0.2

-0.6 -0.4 -0.2 0.0 0.2 0.4

ACF for MA(2) p1=-0.8 p2=0.64


-0.6 -0.4 -0.2 0.0 0.2 0.4

-0.8 -0.6 -0.4 -0.2 0.0 0.2


0

20

10
Lag

15

20

PACF for MA(2) p1=-1.25 p2=0.64


-0.8 -0.6 -0.4 -0.2 0.0 0.2

PACF for MA(1) p=-0.5


-0.8 -0.6 -0.4 -0.2 0.0 0.2

PACF for MA(1) p=-2

-0.6 -0.4 -0.2 0.0 0.2 0.4

-0.6 -0.4 -0.2 0.0 0.2 0.4

ACF for MA(1) p=-2

10
Lag

15

20

10
Lag

15

20

ARMA(p,q) 0 = 0
ARMA(p,q).
xt = 0 + 1 xt 1 + " + p xt p + t 1 t 1 " q t q

p 0 q 0

2
E ( t ) = 0Var ( t ) = , E ( t s ) = 0, s t
Ex = 0, s < t
s t

( B) = 0
,
ARMA(p,q):P
ARMA(p,q)
ARMA(p,q):q ( B) = 0 ,
ARMA(p,q).

AR(P)

MA(q)

ARMA(p,q)

clear
sim_arma y1,ma(0.9) n(1000) time(t)
sim_arma y2,ar(0.1)
sim_arma y3,ma(0.2,0.3,0.8)
sim_arma y4,ma(0.2) ar(-0.7)
tsset t
ac y1,recast(bar) //
pac y1,recast(bar) //
arima y1,ma(1)

chrisccb@126.com

165

STATA 16

arima y1,arima(0,0,1) //
ac y3,recast(bar) //
pac y3,recast(bar) //
arima y3,arima(0,0,3)
arima y3,ma(1/3)
predict uh3, resid
//
corrgram uh3, lags(8) //
predict yh3
tsline y3 yh3 in 100/140
arima y2,arima(0,0,1)
arima y4,arima(1,0,1)

Barlett

1
n

k ~ N (0, ) , n

95

Pr

Pr

Quenouille

1
n

kk ~ N (0, ) , n

2
2
k
0.95
n
n
2
2
kk
0.95
n
n

:() d
95 2
()
d
p + q + 2 1 ," , p , 1 ," , q , , 2

:
,

H 01 = 2 = " = m = 0, m 1

H1 k 0, m 1k m

m
k2
) ~ 2 ( m)
LB = n(n + 2) (
LB
k =1 n k
j j
T
=
n

m
~ t ( n m)

a jj Q(  )

An Information Criterion

chrisccb@126.com

166

STATA 16

AIC

AIC = n ln( 2 ) + 2()

AIC AIC

SBC SBC = n ln( ) + ln(n)()


clear
set obs 200
set seed 1234
sim_arma y, ar(0.9) ma(0.9,0.3,0.5)
arima y , ar(1) ma(1/3)
icomp
//net get icomp
2

16.5
,,,
,
,
,
use http://fmwww.bc.edu/ec-p/data/wooldridge/phillips, clear
tsset year, yearly
set seed 1234
sim_arma u, ar(0.8)
drawnorm x, mean(5) sds(9)
g y=20*x+u
reg y x
dwstat
//dw
durbina //durbinabgodfrey
bgodfrey, lag(1/3)
predict e, res
g e1=e[_n-1]
line e e1, sort
reg e x L(1/3).e
dwstat
bgodfrey, lag(1/3)
prais y x
prais y x, corc
prais y x, twostep
prais y x, ssesearch
prais y x, robust
reg inf unem
predict uh, res

chrisccb@126.com

167

STATA 16

reg uh L.uh
reg inf unem
dwstat
durbina
prais inf unem, ssesearch

wooldbridge (12.3)
use http://fmwww.bc.edu/ec-p/data/wooldridge/barium, clear
tsset t, yearly
reg lchnimp lchempi lgas lrtwex befile6 affile6 afdec6
predict uh, res
reg uh lchempi lgas lrtwex befile6 affile6 afdec6 L(1/3).uh
test L1.uh L2.uh L3.uh
prais lchnimp lchempi lgas lrtwex befile6 affile6 afdec6, corc
use http://fmwww.bc.edu/ec-p/data/wooldridge/PRMINWGE, clear //
newey lprepop lmincov lprgnp lusgnp t, lag(2)
reg lprepop lmincov lprgnp lusgnp t
bgodfrey
bgodfrey , lags(1 2 3)
dwstat
drawnorm x, mean(5) sds(9) clear
sim_arma u, ar(-0.2 -0.8)
//
g y=20*x+u
reg y x
dwstat
durbina, lag(1 2 3) robust
bgodfrey, lag(1/5)
predict e, res
reg e L(1/2).e
reg e L(1/5).e
newey y x, lag(2)
prais y x, ssesearch

16.6
,
clear
sim_arma y, ar(1) n(691) spin(2000) time(t)
tsline y D.y //:
pac y
ac y
reg y L.y
//1,,t. Yt=p*Yt-1+u,p=1
//Yt=p*Yt-1+u,p=1
ttest y==1
reg D.y L.y /*2, Y=(p-1)*Yt-1+u, p*=p-1=0?

chrisccb@126.com

168

STATA 16

,p*t,(Dickey-Fuller
distribution),,*/
dfuller y, lags(0)
//DF
dfuller y, lags(0) regress //DFY=(p-1)*Yt-1+u
dfgls y //
dfgls y, maxlag(3)
pperron y
pperron y, reg
NYSE,,
use nyse, clear
tsset t
*:
corr price L2.price
tsline price D.price
corrgram price, lag(10)
pac price
ac price
dfuller price
dfuller price, lags(0) regress
dfgls price
pperron price
xcorr price return, lags(9)
xcorr price return, lags(9) table
sim_arma y, ar(1) n(691) spin(2000) time(t)
replace y=y+50
tsline price D.price || line y D.y
corrgram y
corrgram price
dfuller y,lags(0) regress
dfuller price,lags(0) regress
/*yu,u,uu
y-u=p(y-1-u)+ey=A+py-1+e=u(1-p),
p=1=0*/
reg y L.y
*,
use nyse, clear
tsset t
g y=49.75 in 1 //
quietly forvalues i=2/691 {
replace y=0.2+y[_n-1]+invnorm(uniform()) in `i'
}
tsline y D.y || tsline price D.price
* : y=b+yt-1+e, y-a-b*t=p(yt-1-a-b*t)+e, y=A+Bt+pyt-1+e,

chrisccb@126.com

169

STATA 16

=a(1-p)+bp,B=b(1-p), p=1=b, B=0


reg y L.y
reg D.y L.y
reg D.y L.y t
dfuller y, lags(0) regress
dfuller price, lags(0) regress
dfuller y, lags(0) trend regress
dfuller price, lags(0) trend regress
/*:xyyt=a+bxt+ut,ut,
,,I(0);XY,
ut=yt-a-bxt,XY.*/
clear
sim_arma x, ar(1) n(200) time(t) spin(2000)
g y=10+0.5*x+invnormal(uniform())
tsline x y
reg y x
predict e, res
dfuller y
dfuller x
dfuller e, regress

clear
capt prog drop bb
prog bb
drop _all
set obs 100
sim_arma x,ar(0.8)
sim_arma y,ar(0.8)
reg y x
test x=0
scalar p1=r(p)
prais y x,corc
test x=0
scalar p2=r(p)
end
quietly simulate p1=p1 p2=p2,reps(1000):bb
gen h1=p1<0.05
g h2=p2<0.05
tab h1
tab h2
*hist h,xline(0.05)


chrisccb@126.com

170

STATA 16

16.7
use nyse, clear
tsset t
rename price y
tssmooth ma y1=y, window(4 0 3) replace
/*window,
,*/
tssmooth ma y2=y, weight(5 1 7 <2> 8) replace
/*weight<>,<>
,<>*/
tssmooth exponential y1=y, parms(0.1) replace //
tssmooth exponential y2=y, parms(0.9) replace
tsline y y1 y2 in 500/600
tssmooth dexponential y1=y, parms(0.1) replace
tssmooth dexponential y2=y, parms(0.9) replace
tsline y y1 y2 in 500/600
tssmooth dexponential y1=y in 500/680, forecast(10) replace //
tssmooth exponential y2=y in 500/680, parms(0.5) forecast(10) replace
tsline y y1 y2 in 650/l
tssmooth hwinters y1=y in 500/680,p (0.3 0.2) f (10) replace //Holt-Winters
tssmooth h y2=y in 500/680, p (0.1 0.9) f (10) replace
tsline y y1 y2 in 650/l
*****Holt-Winters season smoothing
tssmooth shwinters y1=y in 500/680,p (0.3 0.2 .1) period(4) f (10) replace
tssmooth s y2=y in 500/680, p (0.1 0.9 .2) f (10) per (4) replace //HW
tsline y y1 y2 in 650/l
tssmooth nl y1=y in 500/680,smoother(3rssh) replace
tssmooth nl y2=y in 500/680, smoother(4253h,twice) replace
tsline y y1 y2 in 650/l


chrisccb@126.com

171

STATA 17

17
17.1 OLS
1-6 OLS
*===========================begin====================================
clear
set memory 40m
mat m=(3,4,5,0)
mat sd=(9,9.6,0.01,0\9.6,16,12,0\0.01,12,25,0\0,0,0,1)
/*,X1X2(),X1
X3,X2X3,x4,*/
drawnorm x1 x2 x3 x4,n(10) means(m) cov(sd)
gen u=invnorm(uniform())
/*uuN(0,)

10
IID*/
gen y=12+5*x1+10*x2+3*x3+x4+u /*10

10u
Xu

E(u|X)=0, Var(u|X)=9*/
reg y x1 x2 x3 x4
/*
X21095%*/
/*OLS
OLS
620
*/
capt prog drop _all
prog bb
drop _all
drawnorm x1 x2 x3 x4,n(10) means(m) cov(sd)
gen u=invnorm(uniform())
gen y=12+5*x1+10*x2+3*x3+x4+u
quietly reg y x1 x2 x3 x4
end
simulate _b,reps(200): bb
sum _b_x2
//OLS10
pnorm _b_x2 //
swilk _b_x2 //
hist _b_x2
*===========================end====================================


chrisccb@126.com

172

STATA 17

17.2 OLS
1-5 -

OLS
*===========================begin====================================
drop _all
drawnorm x1 x2 x3 x4,n(10) means(m) cov(sd)
rndexp 20 1 //xe
gen y=12+5*x1+10*x2+3*x3+x4+xe /*
E(u|X)=0, Var(u|X)=9*/
reg y x1 x2 x3 x4
/*X210
95%*/
/*OLS
OLS
*/
capt prog drop _all
prog bb
drop _all
drawnorm x1 x2 x3 x4,n(10) means(m) cov(sd)
rndexp 20 1
//
gen y=12+5*x1+10*x2+3*x3+x4+xe
quietly reg y x1 x2 x3 x4
end
simulate _b,reps(200) :bb
sum
//OLS
hist _b_x2
pnorm _b_x2 //,
swilk _b* //
*===========================end====================================

17.3 OLS
1-5 6
100OLS
*===========================begin====================================
drop _all
drawnorm x1 x2 x3 x4,n(10000) means(m) cov(sd)
rndexp 10000 1 //xe
gen y=12+5*x1+10*x2+3*x3+x4+xe /*
*/
reg y x1 x2 x3 x4
/*X21095%*/
/*OLS
OLS
*/
capt prog drop _all
prog bb

chrisccb@126.com

173

STATA 17

drop _all
drawnorm x1 x2 x3 x4,n(10000) means(m) cov(sd)
//
rndexp 10000 1 //xe
gen y=12+5*x1+10*x2+3*x3+x4+xe
quietly reg y x1 x2 x3 x4
end
simulate _b,reps(200) :bb
sum _b_x2
//OLS
qnorm _b_x2
//,
swilk _b* //
*===========================end====================================

1-56
OLS
*===========================begin====================================
mat m=(3,4,5,0)
mat sd=(9,9.6,0.01,0\9.6,16,12,0\0.01,12,25,0\0,0,0,1)
capt prog drop _all
prog bb
drop _all
drawnorm x1 x2 x3 x4,n(20) means(m) cov(sd)
//
gen u=invnorm(uniform())
//
gen y=12+5*x1+10*x2+3*x3+x4+u
quietly reg y x1 x2 x3 x4
end
capt prog drop bb2
prog bb2
drop _all
drawnorm x1 x2 x3 x4,n(20) means(m) cov(sd)
rndexp 20 1
//
gen y=12+5*x1+10*x2+3*x3+x4+xe
quietly reg y x1 x2 x3 x4
end

//

capt prog drop bb3


prog bb3
drop _all
drawnorm x1 x2 x3 x4,n(10000) means(m) cov(sd)
rndexp 10000 1
//
gen y=12+5*x1+10*x2+3*x3+x4+xe
quietly reg y x1 x2 x3 x4
end

//

simulate _b, reps(200) :bb


mkmat _b_x2,mat(A)
simulate _b, reps(200): bb2
mkmat _b_x2, mat(B)
mat A=(nullmat(A),B)

chrisccb@126.com

174

STATA 17

simulate _b,reps(200) :bb3


mkmat _b_x2, mat(B)
mat A=(nullmat(A),B)
svmat A
pnorm A1 //OLS
pnorm A2 //OLS
pnorm A3 //OLS
swilk A*
//
sum A*
//
*===========================end====================================

17.4
OLS

*===========================begin====================================
*
capt prog drop _all
prog bb
drop _all
drawnorm x1 x2 x3 x4,n(100) means(m) cov(sd)
gen u=invnorm(uniform())
gen y=12+5*x1+10*x2+5*x2^2+3*x3+x4+u
quietly reg y x1 x2 x3 x4
//
end
simulate _b,reps(200) : bb
sum _b_z
//OLS
*===========================end=====================================
*===========================begin====================================
*
drawnorm x1 x2 x3 x4,n(100) means(m) cov(sd)
gen u=invnorm(uniform())
gen y=12+5*x1+10*x2+5*x2^2+3*x3+x4+u
quietly reg y x1 x2 x3 x4
//
ovtest
//
ovtest, rhs
gen z=x2^2
quietly reg y x1 x2 z x3 x4
//
sum _b_z
//OLS
*===========================end=====================================


chrisccb@126.com

175

STATA 17

17.5
OLS

*===========================begin=============================
drop _all
drawnorm x2 x3 x4,n(1000) means(m) cov(sd)
gen u=3*invnorm(uniform())
gen y=5*x1+10*x2+3*x3+x4+u /**/
sort y
keep in 1/50
/**/
reg y x1 x2 x3 x4
/*1095%*/
*===========================end====================================

*================truncated model===========begin==================
drop _all
drawnorm x2,n(1000)
gen u=9*invnorm(uniform())
gen y=-5+10*x2+u /**/
drop if y<0
reg y x2
/*1095%*/
truncreg y x2,ll(0)
*===========================end====================================
*================sensored model===========begin==================
drop _all
drawnorm x2,n(1000)
gen u=9*invnorm(uniform())
gen y=-5+10*x2+u /**/
replace y=0 if y<0
reg y x2
/*1095%*/
truncreg y x2,ll(0)
*===========================end====================================

*===========================begin==================
drop _all
drawnorm x2,n(1000)
gen u=9*invnorm(uniform())
gen y=-5+10*x2+u /**/
replace y=-10000 in 100
reg y x2
/*1095%*/
rreg y x2
*===========================end====================================


chrisccb@126.com

176

STATA 17

17.6
OLS

*===========================begin====================================
* E(u|x) !=0
capt prog drop _all
prog bb
drop _all
drawnorm x1 x2 x3 x4,n(100) means(m) cov(sd)
gen u=3*invnorm(uniform())
gen y=12+5*x1+10*x2+3*x3+x4+u
quietly reg y x2 x3 x4
//x1
end
simulate _b,reps(200) :bb
sum
//OLS
*
capt prog drop _all
prog bb
drop _all
drawnorm x1 x2 x3 x4,n(100) means(m) cov(sd)
gen u=invnorm(uniform())
gen y=12+5*x1+10*x2+3*x3+x4+u
quietly reg y x1 x2 x3
//x4
end
simulate _b,reps(200) : bb
sum
//OLS
*===========================end====================================

17.7

*===========================begin====================================
drop _all
drawnorm x1 x2 x3 x4,n(100) means(m) cov(sd)
gen u=3*invnorm(uniform())
gen y=12+5*x1+10*x2+3*x3+x4+u
gen x5=3*x2+x1
reg y x1 x2 x3 x4 x5
//STATA
*===========================end====================================

17.8
15 16

chrisccb@126.com

177

STATA 17


chrisccb@126.com

178

STATA 18

18 4
18.1
/*

testscore=a+b*classsize+u
caschool.dta
1998-1999 420 K6 K8 , 9

*/
*===========================begin====================================
*
clear
cap log close
*************************************************************
* stock 2006 12 24
*************************************************************
log using scoresize.log,replace
set more off
***********************************
*
cd F:\\STATA
use caschool.dta
*******************************
* dist_code
* Read_scr --
* Math_scr --
* County --
* District
* gr_span
* enrl_tot
* teachers
* computer
* testscr (= (read_scr+math_scr)/2 )
* comp_stu ( = computer/enrl_tot)
* expn_stu
4

stock introduction to Economitrics



chrisccb@126.com

179

STATA 18

* str (teachers/enrl_tot)
* el_pct
* Meal_pct
* clw_pct
* aving (in $1000's)
***** 1998 420 ******
sum str str
//
pctile pct_tsc = testscr, nq(20) genp(pctx)
// 20
pctile pct_str = str, nq(20)
list pctx pct_str pct_tsc in 1/20
** 10 17.3, 10% 17.3.
**********
cor str testscr
*-0.23,
***** ******
tw (scatter testscr str,sort) (lfit testscr str)
***********
reg testscr str, r
/*-2.28, 1 2.28
19.7,
654.5 2 50
10 4.6 60

*/
gen d = (str<20)
reg testscr d, r
/* 1998 420

2 4.6
50 60

5% 0.
0 0.001%

OLS


chrisccb@126.com

180

STATA 18

18.2

*/
use caschool.dta, clear
*******************************************
/*20
t*/
gen str_20 = (str<20)
//
gen ts_lostr = testscr if str_20==1
gen ts_histr = testscr if str_20==0
xtile elq=el_pct,nq(4)
table str_20 elq,c(mean testscr) format(%5.2f)
ttest ts_lostr=ts_histr, unp une
//t
by elq,sort: ttest ts_lostr=ts_histr, unp une //t
anov testscr str_20
//
/*
7.41%

1.34.3
4.91.9

*/
*********************************************
reg testscr str, r
//
esti store model1
reg testscr str el_pct, r //
esti store model2
/*OLS-1.10,-2.28
1
*/
/*


chrisccb@126.com

181

STATA 18

*/
replace expn_stu = expn_stu/1000
//
reg testscr str expn_stu el_pct, r
esti store model3
/*
-0.29,

*/
test str expn_stu
/*F5.43,1%
*/
******* **************************************************
cor testscr str expn_stu el_pct meal_pct calw_pct
**************************************************
reg testscr str, r
esti store model1
reg testscr str el_pct, r //
esti store model2
reg testscr str el_pct meal_pct, r //
esti store model3
reg testscr str el_pct calw_pct, r //
esti store model4
reg testscr str el_pct meal_pct calw_pct, r
esti store model5
esti table model*, stats(r2_a N) b (%5.2f) se (%5.3f)
/*
5%
25
1 1
0.049,
R 3 0.773.
5
5%3

18.3

*/
*


chrisccb@126.com

182

STATA 18

use caschool.dta, clear


***** ************
gen avginc2 = avginc*avginc
gen avginc3 = avginc2*avginc
gen loginc = ln(avginc)
gen logtest = ln(testscr)
gen loginc2 = loginc*loginc
gen loginc3 = loginc2*loginc
gen histr = (str>=20)
gen hiel = (el_pct >= 10)
gen hisxhie = histr*hiel
gen strxhiel = str*hiel
gen strxelpc = str*el_pct
gen sttr2 = str*str
gen sttr3 = sttr2*str
gen str2hiel = sttr2*hiel
gen str3hiel = sttr3*hiel
reg testscr str el_pct meal_pct, r
//
esti store model1
reg testscr str el_pct meal_pct loginc, r //
esti store model2
reg testscr str hiel strxhiel, r //
esti store model3
test str strxhiel // F P
reg testscr str hiel strxhiel meal_pct loginc, r //
esti store model4
test str strxhiel
// F P
reg testscr str sttr2 sttr3 hiel meal_pct loginc, r //
esti store model5
test str sttr2 sttr3 // F P
test sttr2 sttr3 // F P
reg testscr str sttr2 sttr3 hiel strxhiel str2hiel str3hiel meal_pct loginc, r //
esti store model6
test str sttr2 sttr3 strxhiel str2hiel str3hiel // F P
test sttr2 sttr3 // F P
test strxhiel str2hiel str3hiel
// F P
reg testscr str sttr2 sttr3 el_pct meal_pct loginc, r //
esti store model7
test str sttr2 sttr3 // F P
test sttr2 sttr3 // F P
esti table model*, stats(r2_a N) b (%5.2f) se (%5.3f)
/*12
1% 0,-0.73,
1%

4 5%


chrisccb@126.com

183

STATA 18

5
1%
6

F 1%
75
5

1%

18.4

*/
***********************************;
use mcas.dta, clear
* code
District Code (numerical)
* municipa
Municipality (name)
* district
District Name
* totsc4
4th grade score (math+english+science)
* totsc8
8th grade score (math+english+science)
* regday
Spending per pupil, regular
* specneed
Spending per pupil, special needs
* bilingua
Spending per pupil, bilingual
* occupday
Spending per pupil, occupational
* tot_day
Spending per pupil, Total
* tchratio
Students per Teacher
* s_p_c
Students per Computer
* spec_ed
% Special Education Students
* lnch_pct
% Eligible for free/reduced price lunch
* avgsalry
Average Teacher Salary
* percap
Per Capita Income
* pctel
Percent English Learners

chrisccb@126.com

184

STATA 18

******************************;
* rename variables -- same as CA dataset
gen str = tchratio
gen testscr=totsc4
gen el_pct = pctel
gen avginc = percap
gen meal_pct = lnch_pct
gen avginc2 = avginc*avginc
gen avginc3 = avginc2*avginc
gen loginc = ln(avginc)
gen hiel = (el_pct > 0)
gen strxhiel = str*hiel
gen sttr2 = str*str
gen sttr3 = sttr2*str
***************;
sum testscr str el_pct meal_pct avginc
sum el_pct, d
**** 4*************
reg testscr str, r
esti store m1
reg testscr str el_pct meal_pct loginc, r
esti store m2
reg testscr str el_pct meal_pct avginc avginc2 avginc3, r
esti store m3
test avginc2 avginc3
reg testscr str sttr2 sttr3 el_pct meal_pct avginc avginc2 avginc3, r
esti store m4
test str sttr2 sttr3
test sttr2 sttr3
test avginc2 avginc3
reg testscr str hiel strxhiel meal_pct avginc avginc2 avginc3, r
esti store m5
test str strxhiel
test avginc2 avginc3
test hiel strxhiel
reg testscr str meal_pct avginc avginc2 avginc3, r
esti store m6
test avginc2 avginc3
esti table m*, stats(r2_a N) b (%5.2f) se (%5.3f)
/*

2 1.1%
15.8%
420 220
3
1 68%-0.7 -0.6
2 1% 5%


chrisccb@126.com

185

STATA 18

2
0.076, 2 0.085. 2
0.08

12
95%
OLS

OLS

1 A
B C

A B C

3A X
B
4 heckman.
5

A B
OLS
1 2

HAC

1990 1998/1999


chrisccb@126.com

186

STATA 18

18.5
20 80 1200
Student-Teacher Achievement, STAR

STAR 1985-1986
2225
1317

6400
108 101 99 4 80
11600
10%

01smallclass2regaide+u
tscorek sck rak ,
*/
**************************************************
use star_sw.dta, clear
************************************************
*----- ----sum tscorek sck rak if stark==1
reg tscorek sck rak if stark==1, r
*----- ----sum tscore1 sc1 ra1 if star1==1
reg tscore1 sc1 ra1 if star1==1, r
*----- ----sum tscore2 sc2 ra2 if star2==1
reg tscore2 sc2 ra2 if star2==1, r
*----- ----sum tscore3 sc3 ra3 if star3==1
reg tscore3 sc3 ra3 if star3==1, r
/*

13.9
0.31 1%

*/
*******************************
preserve
keep if stark==1
reg tscorek sck rak, r
est store m1


chrisccb@126.com

187

STATA 18

reg tscorek sck rak totexpk, r // totexpk


est store m2
areg tscorek sck rak totexpk, r absorb(schidkn) //
esti store m3
* boy freelunk black, other,
areg tscorek sck rak totexpk boy freelunk black other, r absorb(schidkn)
esti store m4
esti table m*, stats(r2_a N) b (%5.2f) se (%5.3f)
table sck,c(m totexpk m boy m freelunk m black m other)
log close
*==========================end====================================
/*
R 2.45 2.16*/


chrisccb@126.com

188

STATA 18

clear
matrix m=(1,2,3,4)
drawnorm x1-x4,n(1000) m(m) //
gen n=_n
reshape long x,i(n) j(m)
gen y=x
replace y=. if y>=4
//4
gen z=normalden(y,m,1)*(1-normal(y-m)) //
g f=normalden(x,m,1)
tw (line f z x,sort) (kdensity y) ,by(m) xline(4)

clear
matrix m=(1,2,3,4)
drawnorm x1-x4,n(1000) m(m)
gen n=_n
reshape long x,i(n) j(m)
gen y=x
replace y=4 if y>=4
//4
gen z=normalden(y,m,1)*(1-normal(y-m))
g f=normalden(x,m,1)
tw (line f z x,sort) (kdensity y) ,by(m) xline(4)


chrisccb@126.com

189

Anda mungkin juga menyukai