Teach Yourself Stata
Teach Yourself Stata
Teach Yourself Stata
usingStata
(ver.4.6)
OscarTorresReyna
DataConsultant
[email protected]
http://dss.princeton.edu/training/
PU/DSS/OTR
Listoftopics
WhatisStata?
Statascreenandgeneraldescription
Firststeps(log,memoryanddirectory)
FromSPSS/SAStoStata
ExampleofadatasetinExcel
FromExcel toStata (copyandpaste,*.csv)
Savingthedataset
Describe andsummarize (command,menu)
Rename andlabelvariables (command,menu)
Creatingnewvariables(generate)
Recodingvariables(recode)
Recodingvariablesusingegen
Changingvalues(replace)
Extractingcharactersfromregularexpressions
Valuelabelsusingthemenu
Indexing (using_nand_N)
9 Creatingidsandidsbycategories
9 Lagsandforwardvalues
9 Countdownandspecificvalues
Sorting
Deletingvariables(drop)
Merge
Append
Mergingfuzzytext(reclink)
FrequentlyusedStatacommands
Exploringdata:
9 Frequencies(tab,table)
9 Crosstabulations(withtestforassociations)
9 Descriptivestatistics(tabstat)
Examplesoffrequenciesandcrosstabulations
Creatingdummies
Graphs
9 Scatterplot
9 Histograms
9 Catplot(forcategoricaldata)
9 Bars(graphingmeanvalues)
Regression:
9 Overviewandbasicsetting
9 Correlationmatrix
9 Outputinterpretation(whattolookfor)
9 Graphmatrix
9 Savingregressioncoefficients
9 Ftest
9 Testingforlinearity
9 Testingfornormality
9 Testingforhomoskedasticity
9 Testingforomittedvariablebias
9 Testingformulticolinearity
9 Robuststandarderrors
9 Specificationerror
9 Outliers
9 Summaryofinfluenceindicators
9 Summaryofdistancemeasures
9 Interactionterms
9 Publishingregressiontable(outreg2)
Usefulsites(linksonly)
9 IsmymodelOK?
9 Icantreadtheoutputofmymodel!!!
9 TopicsinStatistics
9 Recommendedbooks
PU/DSS/OTR
What is Stata?
Itisamultipurposestatisticalpackagetohelpyouexplore,summarizeand
analyzedatasets.
Adataset isacollectionofseveralpiecesofinformationcalledvariables(usually
arrangedbycolumns).Avariablecanhaveoneorseveralvalues(informationfor
oneorseveralcases).
OtherstatisticalpackagesareSPSS,SASandR.
Stataiswidelyusedinsocialscienceresearchandthemostusedstatistical
softwareoncampus.
Features
Stata
SPSS
SAS
Learning curve
Steep/gradual
Gradual/flat
Pretty steep
Pretty steep
User interface
Programming/point-and-click
Mostly point-and-click
Programming
Programming
Very strong
Moderate
Very strong
Very strong
Powerful
Powerful
Powerful/versatile
Powerful/versatile
Very good
Very good
Good
Good
Affordable (perpetual
licenses, renew only when
upgrade)
Expensive (yearly
renewal)
Open source
Data manipulation
Data analysis
Graphics
Cost
PU/DSS/OTR
PU/DSS/OTR
PU/DSS/OTR
Firststeps
Three basic procedures you may want to do first:
Set your working directory (see next slide for more info)
Create a log file (sort of Statas built-in tape recorder and where you
can retrieve the output of your work)
Using the menu go to File Log Begin (see the next slide for
more info)
In the command line type log using mylog.log. This will
create a file called mylog.log in your directory which you can
read using any word processor.
Set the correct memory allocation for your data. Some datasets more
memory, depending on the size you can type set mem 700m to open
the big ones
PU/DSS/OTR
ClickonSaveastype:rightbelowFilename:
andselectLog(*.log). Thiswillcreatethefile
calledLog1.log(orwhatevernameyouwantwith
extension*.log)whichcanbereadbyanyword
processororbyStata(gotoFile Log View).If
yousaveitas*.smcl(FormattedLog)onlyStata
canreadit.Itisrecommendedtosavethelogfile
as*.log
2
Shows your current working directory.
You can change it by typing
cd c:\mydirectory
Whendealingwithreallybigdatasetsyoumaywanttoincreasethememory:
set mem 700m
Toestimatethesizeofthefileyoucanusetheformula:
Size(inbytes)=(8*Numberofcasesorrows*(Numberofvariables+8))
PU/DSS/OTR
FromSPSS/SAStoStata
Youcanusethecommandusespss toreadSPSSfilesinStataor
thecommandusesas toreadSASfiles.IfyouhaveafileinSAS
XPORTyoucanusefduse (orgotofileimport).ForSPSS,you
mayneedtoinstallitbytyping
ssc install usespss
Onceinstalledjusttype
usespss using c:\mydata.sav
Typehelp usespss formoredetails.
ThereisasimilarcommandforSAS(usesas),justrepeatthe
previoussteps.
ForASCIIdatapleaseseetheStatamoduleat
http://dss.princeton.edu/training/
PU/DSS/OTR
1 TogofromExceltoStata yousimplycopyand
pastedataintotheStatasDataeditorwhich
youcanopenbyclickingontheiconthatlooks
likethis:
2 Thiswindowwillopen,isthedataeditor
3 PressCtrlvtopastethe
data
PU/DSS/OTR
1 ClosethedataeditorbypressingtheXbuttonontheupperrightcorneroftheeditor
NOTE: You need to close
the data editor or data
browser to continue
working.
2 TheVariables
windowwillshowall
thevariablesinyour
data
4 Thisiswhatyouwillseeintheoutputwindow,
thedatahasbeensavedasstudents.dta
PU/DSS/OTR
InStata gotoFileImportASCIIdatacreatedbyspreadsheet.ClickonBrowsetofindthefileandthenOK.
2
PU/DSS/OTR
To start exploring the data well use two commands: describe and summarize
1 - If you type describe in
the command window you
will get a general description
of the data (press enter after
you type).
To describe the data go to Data Describe data Describe data in memory and press OK
To summarize the data go to Data Describe data Summary statistics and press OK
PU/DSS/OTR
Exploringdata:frequencies
Frequencyreferstothenumberoftimesavalueisrepeated.Frequenciesareusedtoanalyze
categoricaldata.Thetablesbelowarefrequencytables,valuesareinascendingorder.InStatause
thecommandtab (typehelp tab formoredetails)
variable
Freq.providesarawcountofeachvalue.Inthiscase10
studentsforeachmajor.
Percentgivestherelativefrequencyforeachvalue.For
example,33.33%ofthestudentsinthisgroupareecon
majors.
Cum.isthecumulativefrequencyinascendingorderof
thevalues.Forexample,66.67%ofthestudentsare
econormathmajors.
variable
Freq.Here6studentsreadthenewspaper3daysa
week,9studentsreadit5daysaweek.
Percent.Thosewhoreadthenewspaper3daysaweek
represent20%ofthesample,30%ofthestudentsinthe
samplereadthenewspaper5daysaweek.
Cum.66.67%ofthestudentsreadthenewspaper3to5
daysaweek.
PU/DSS/OTR
Exploringdata:frequencies(usingtable)
var1
var2
PU/DSS/OTR
Exploringdata:crosstabs
Alsoknownascontingencytables,helpyoutoanalyzetherelationshipbetweentwoormore
variables(mostlycategorical).Belowisacrosstabbetweenthevariableecostatuandgender.We
usethecommandtab (butwithtwovariablestomakethecrosstab).
Optionscol,rowgivesyouthecolumn
androwpercentages.
var1
var2
Thefirstvalueinacelltellsyouthenumberof
observationsforeachxtab.Inthiscase,90
respondentsaremaleandsaidthatthe
economyisdoingverywell,59arefemale
andbelievetheeconomyisdoingverywell
Thesecondvalueinacellgivesyourow
percentagesforthefirstvariableinthextab.
Outofthosewhothinktheeconomyisdoing
verywell,60.40%aremalesand39.60%are
females.
Thethirdvalueinacellgivesyoucolumn
percentagesforthesecondvariableinthextab.
Amongmales,14.33%thinktheeconomyis
doingverywellwhile7.92%offemaleshave
thesameopinion.
Exploringdata:crosstabs(acloserlook)
Youcanusecrosstabstocompareresponsesamongcategoriesinrelationtoaggregate
responses.Inthetablebelowwewillseewhethermalesandfemaleshaveopinions
similartothenationalaggregate.
Asaruleofthumb,amarginoferrorof4percentagepointscanbe
usedtoindicateasignificantdifference(someuse3).
Forexample,roundingupthepercentages,11%(10.85)answervery
wellatthenationallevel.Withthemarginoferror,thisgivesarange
roughlybetween7%and15%,anythingbeyondthisrangecouldbe
consideredsignificantlydifferent(rememberthisisjustan
approximation).Itdoesnotappeartobeasignificantbiasbetween
malesandfemalesforthisanswer.
Inthefairlywellcategorywehave49%,withrangebetween45%
and53%.Theresponseformalesis54%andforfemales45%.We
couldsayherethatmalestendtobeabitmoreoptimisticonthe
economyandfemalestendtobeabitlessoptimistic.
Ifweaggregateresponses,wecouldgetabetterpicture.Inthetable
below68%ofmalesbelievetheeconomyisdoingwell(comparingto
60%atthenationallevel,while46%offemalesthingtheeconomyis
bad(comparingto39%aggregate).Malesseemtobemoreoptimistic
thanfemales.
Exploringdata:crosstabs(testforassociations)
Toseewhetherthereisarelationshipbetweentwovariablesyoucanchooseanumberof
tests.Someapplytonominal variablessomeotherstoordinal.Iamrunningallofthem
hereforpresentationpurposes.
Likelihoodratio2(chisquare)
X2(chisquare)
Goodman&Kruskals (gamma)
CramersV
Fishersexacttest
Kendallsb (taub)
Fornominal datausechi2,lrchi2,V
Forordinal datausegammaandtaub
Useexact insteadofchi2 when
frequenciesarelessthan5acrossthe
table.
X2(chisquare)testsforrelationshipsbetweenvariables.Thenull
hypothesis(Ho)isthatthereisnorelationship.Torejectthisweneeda
Pr<0.05(at95%confidence).Herebothchi2aresignificant.Therefore
weconcludethatthereissomerelationshipbetweenperceptionsofthe
economyandgender
CramersVisameasureofassociationbetweentwonominalvariables.It
goesfrom0to1where1indicatesstrongassociation(forrXctables).In
2x2tables,therangeis1to1.HeretheVis0.15,whichshowsasmall
association.
Gammaandtaubaremeasuresofassociationbetweentwoordinal
variables(bothhavetobeinthesamedirection,i.e.negativetopositive,
lowtohigh).Bothgofrom1to1.Negativeshowsinverserelationship,
closerto1astrongrelationship.Gammaisrecommendedwhenthere
arelotsoftiesinthedata.Taubisrecommendedforsquaretables.
Fishersexacttestisusedwhenthereareveryfewcasesinthecells
(usuallylessthan5).Itteststherelationshipbetweentwovariables.The
nullisthatvariablesareindependent.Herewerejectthenulland
concludethatthereissomekindofrelationshipbetweenvariables
PU/DSS/OTR
Exploringdata:descriptivestatistics
Forcontinuousdataweusedescriptivestatistics.Thesestatisticsareacollectionofmeasurementsof
twothings:location andvariability.Locationtellsyouthecentralvalueofyourvariables(themeanis
themostcommonmeasureofthis).Variabilityreferstothespreadofthedatafromthecentervalue
(i.e.variance,standarddeviation).Statisticsisbasicallythestudyofwhatcausessuchvariability.We
usethecommandtabstat togetthesestats.
Themean isthesumoftheobservationsdividedbythetotalnumberofobservations.
Themedian (p50inthetableabove)isthenumberinthemiddle.Togetthemedianyouhavetoorderthedata
fromlowesttohighest.Ifthenumberofcasesisoddthemedianisthesinglevalue,foranevennumberofcases
themedianistheaverageofthetwonumbersinthemiddle.
Thestandarddeviation isthesquaredrootofthevariance.Indicateshowclosethedataistothemean.Assuming
anormaldistribution,68%ofthevaluesarewithin1sdfromthemean,95%within2sdand99%within3sd
Thevariance measuresthedispersionofthedatafromthemean.Itisthesimplemeanofthesquareddistance
fromthemean.
Count (Ninthetable)referstothenumberofobservationspervariable.
Range isameasureofdispersion.Itisthedifferencebetweenthelargestandsmallestvalue,max min.
Min isthelowestvalueinthevariable.
Max isthelargestvalue inthevariable.
PU/DSS/OTR
Exploringdata:descriptivestatistics
Youcouldalsoestimatedescriptivestatisticsbysubgroups.Forexample,bygenderbelow
Crosstabulations
PU/DSS/OTR
PU/DSS/OTR
After
var1
var2
var3
var4
var5
id
country
party
imports
exports
After
label
label
label
label
label
variable
variable
variable
variable
variable
id "Unique identifier"
country "Country name"
party "Political party in power"
imports "Imports as % of GDP"
exports "Exports as % of GDP"
PU/DSS/OTR
PU/DSS/OTR
You can also use generate with string variables. For example:
results for the first five students
generate fullname = last + , + first
label variable fullname Student full name
browse id fullname last first
PU/DSS/OTR
Recoding variables
PU/DSS/OTR
You could also use the option group, which specifies groups with equal frequency (you have to add value
labels:
egen [newvar] = cut (oldvar), group(number of groups)
After
Before
After
Before
After
PU/DSS/OTR
Extractingcharactersfromregularexpressions
To remove strings from var1 below use the following command
gen var2=regexr(var1,"[.\}\)\*a-zA-Z]+","")
destring var2, replace
PU/DSS/OTR
Using _N you can also create a variable with the total number of cases in your
dataset:
PU/DSS/OTR
PU/DSS/OTR
You can create lagged values with _n . Lets rename idall as months (time
variable) and will create a lagged variable containing the value of the previous
case:
Check the results in the data editor:
If you want to lag more than one period just change [_n-1] to [_n-2] for a lag of
two periods, [_n-3] for three, etc.
A more advance alternative to create lags uses the L operand within a time
series setting (tset command must be specified first)
PU/DSS/OTR
You can create a variable based on one value of another variable. For example,
lets create a variable with the highest SAT value in the sample.
Check the results in the data editor:
NOTE: You could get the same result without sorting by using
egen and the max function
PU/DSS/OTR
Sorting
Before
sort var1 var2
After
Gsort is another command to sort data. The difference between gsort and
sort is that with gsort you can sort in ascending or descending order, while
with sort you can sort only in ascending order. Use +/- to indicate whether you
want to sort in ascending/descending order. Here are some examples:
PU/DSS/OTR
We have created lots of variables, now we need to do some clean up. Two
commands can do this: drop and keep.
Deleting variables
Before
After
Or
Notice the dash between total and readnews2, you can use this format to indicate a list so you
do not have to type in the name of all the variables
PU/DSS/OTR
The option nolabel gives you the numeric codes for each country/year
PU/DSS/OTR
We want to keep data for United States (1999) only. The code is 8401999 (see above). To do this we type
drop if s025!=8401999
NOTE: you can drop cases with missing values by typing: drop if missing(var1, var2, var3, )
PU/DSS/OTR
Merge/Append
MERGE - You merge when you want to add more variables to an existing dataset.
(type help merge in the command window for more details)
What you need:
Step 1. You need to sort the data by the id or ids common to both files you want to merge. For both datasets type:
Step 2. Open the master data (main dataset you want to add more variables to, for example data1.dta) and type:
tab _merge
_merge==2
_merge==3
If you want to keep the observations common to both datasets you can drop the rest by typing:
drop if _merge!=3
APPEND - You append when you want to add more cases (more rows to your data, type help append for more details).
Open the master file (i.e. data1.dta) and type:
PU/DSS/OTR
Mergingfuzzytext(reclink)
RECLINK - Matching fuzzy text. Reclink stands for record linkage. It is a program written by Michael Blasnik to merge imperfect
string variables. For example
Data1
Data2
Princeton University
PrincetonU
Reclink helps you to merge the two databases by using a matching algorithm for these types of variables. Since it is a user
created program, you may need to install it by typing ssc install reclink. Once installed you can type help reclink
for details
As in merge, the merging variables must have the same name: state, university, city, name, etc. Both the master and the using
files should have an id variable identifying each observation.
Note: the name of ids must be different, for example id1 (id master) and id2 (id using). Sort both files by the matching (merging)
variables. The basic sytax is:
reclink var1 var2 var3 using myusingdata, gen(myscore) idm(id1) idu(id2)
The variable myscore indicates the strength of the match; a perfect match will have a score of 1. Description (from reclink help
pages):
reclink uses record linkage methods to match observations between two datasets where no perfect key fields exist -essentially a fuzzy merge. reclink allows for user-defined matching and non-matching weights for each variable and
employs a bigram string comparator to assess imperfect string matches.
The master and using datasets must each have a variable that uniquely identifies observations. Two new variables are
created, one to hold the matching score (scaled 0-1) and one for the merge variable. In addition, all of the
matching variables from the using dataset are brought into the master dataset (with newly prefixed names) to allow
for manual review of matches.
PU/DSS/OTR
Graphs:scatterplot
Scatterplotsaregoodtoexplorepossiblerelationshipsorpatternsbetweenvariables.Letsseeifthereissomerelationship betweenage
andSATscores.Formanymorebellsandwhistlestypehelp scatter inthecommandwindow.
twoway scatter age sat
PU/DSS/OTR
Graphs:scatterplot
By categories
twoway scatter age sat, mlabel(last) by(major, total)
PU/DSS/OTR
Graphs:histogram
Histogramsareanothergoodwaytovisuallyexploredata,especiallytocheckforanormal
distribution;herearesomeexamples(typehelphistograminthecommandwindowforfurther
details):
histogram age, frequency
PU/DSS/OTR
Graphs:catplot
Catplot is used to graph categorical data. Since it is a user defined program you may
have to install it typing: ssc install catplot
Now, type
tab agegroups major, col row cell
Graphs:catplot
catplot
catplot
blabel(bar)
blabel(bar)
PU/DSS/OTR
Graphs:catplot
Graphs: means
Stata can also help to visually present
summaries of data. If you do not want to
type you can go to graphics in the menu.
PU/DSS/OTR
Regression:apracticalapproach(intro)
In this section we will explore some basics of regression analysis.
We will run a multivariate regression and some diagnostics :
PU/DSS/OTR
Regression:apracticalapproach(overview)
Weuseregressiontoestimatetheunknowneffect ofchangingonevariableover
another(StockandWatson,2003,ch.4)
Whenwerunaregressionweassumealinearrelationshipbetweentwovariables(i.e.
X andY).Technically,itestimateshowmuchY changeswhenX changesoneunit.
InStataweusethecommandregress, type:
regress [dependent variable] [independent variable(s)]
regress y x
In a multivariate setting we type:
regress y x1 x2 x3
Before running a regression it is recommended to have a clear idea of what you
are trying to estimate (i.e. which are your dependent and independent
variables).
A regression makes sense only if there is a sound theory behind it.
PU/DSS/OTR
Regression:apracticalapproach(overview)cont.
DataandexamplesforthissectioncomefromthebookStatisticswithStata(updated
forversion9) byLawrenceC.Hamilton(chapter6).Clickheretodownloadthedataor
searchforitathttp://www.duxbury.com/highered/.Usethefilestates.dta
(educationaldatafortheU.S.).
PU/DSS/OTR
Regression:apracticalapproach(setting)
Startingquestion:AreSATscoreshigherinstatesthatspendmoremoneyoneducationcontrollingby
otherfactors?
Independent(orpredictor,X)variable(s) Expendituresoneducation,variableexpense
indataset.Othervariablespercent, income, high, college.
Here is a general description of the variables in the model
Regression:graphmatrix
Beforerunningaregressionisalwaysrecommendedtographdependentandindependent
variablestoexploretheirrelationship.Commandgraph matrix producesaseriesof
scatterplotsforallvariables.Type:
graph matrix expense percent income high college csat
Y
Y
PU/DSS/OTR
Regression:graphmatrix
Hereisanotheroptionforthegraph.
graph matrix csat expense percent income high college, half
maxis(ylabel(none) xlabel(none))
PU/DSS/OTR
Regression:whattolookfor
Robust standard errors (to control
Lets run the regression:
for heteroskedasticity)
regress csat expense percent income high college, robust
Dependent
variable (Y)
Independent
variables (X)
3
6
4
5
PU/DSS/OTR
Regression:exploringrelationships
Giventhepreviousresults,weneedtodosomeadjustmentssinceonlyonevariablewas
significant.Letsexplorefurthertherelationshipbetweencsat andpercent, andhigh.
scatter csat percent
Regression:functionalform/linearity
Asafootnote,anothergraphicalwaytoexploreapossiblelinearrelationshipbetweenvariablesortodetect
nonlinearitytodefineafunctionalformisbyusingthecommandacprplot (augmentedcomponentplusresidual
plot).Rightafterrunningatheregression:
regress csat percent high /* Notice we do not include percent2 */
acprplot percent, lowess
Theoptionlowess (locallyweightedscatterplotsmoothing)drawtheobservedpatterninthedatatohelpidentify
nonlinearities.Percent showsaquadraticrelation,itmakessensetoaddasquareversionofit.High showsa
polynomialpatternaswellbutgoesaroundtheregressionline(exceptontheright).Wecouldkeepitasisfornow.
Regression:Ftest
Beforewecontinueletstakeanotherlookattheoriginalregressionandrunsomeindividualtestsonits
coefficients.
Wehavetwotypesoftestswiththeregressionmodel:Ftest,whichteststheoverallfitofthemodel(all
coefficientsdifferentfrom0)andttest(individualcoefficientsdifferentfrom0).Youcancustomizeyour
teststocheckforotherpossiblesituations,liketwocoefficientsjointlydifferentfrom0.Inthe
regression,twovariablesrelatedtoeducationalattainmentwerenotsignificant.Wecould,however,
testwhetherthesetwohavenoeffectonSATscores(seeHamilton,2006,p.175).Letsruntheoriginal
regressionagain:
quietly regress csat expense percent income high college
Note quietly suppress the regression output
The p-value is 0.0451, under the 0.05 usual threshold (95% confidence) so we conclude that both variables
have indeed some effect on SAT. In a way, this is saying that both have similar effect or measuring the same
thing (which could suggest multicolinearity). We could keep high since it was borderline significant.
Some other possible tests are (see Hamilton, 2006, p.176):
test income = 1
test high = college
test income = (high + college)/100
Note: Not to be confused with ttest. Type help test and help ttest for more details
PU/DSS/OTR
Regression:output
Letstrythenewmodel.IthasnowahigherRsquared(0.92)andallthevariablesaresignificant.
Regression:savingregressioncoefficients/gettingpredictedvalues
Stata temporarily stores the coefficients as _b[varname], so if you type:
You can save the coefficients as variables by typing:
gen
gen
gen
gen
percent_coeff = _b[percent]
percent_coeff = _b[percent2]
high_coeff = _b[high]
constant_coeff = _b[_cons]
How good the model is will depend on how well it predicts Y and on the validity of the tests.
There are two ways to generate the predicted values of Y (usually called Yhat) given the model:
Option A, using generate after running the regression:
generate csat_predict = _b[_cons] + _b[percent]*percent + _b[percent2]*percent2 + _b[high]*high
PU/DSS/OTR
Regression:observedvs.predictedvalues
Now lets see how well we did, type
scatter csat csat_predict
PU/DSS/OTR
Regression:testingfornormality
A main assumption of the regression model (OLS) that guarantee the validity of all tests (p, t and F) is that residuals behave
normal. Residuals (here indicated by the letter e) are the difference between the observed values (Y) and the predicted values
(Yhat): e = Y Yhat.
In Stata you type: predict e, resid
It will generate a variable called e (residuals).
Three graphs will help us check for normality in the residuals: kdensity, pnorm and qnorm.
kdensity e, normal
A kernel density plot produces a kind of histogram for the
residuals, the option normal overlays a normal distribution to
compare. Here residuals seem to follow a normal distribution.
Below is an example using histogram.
histogram e, kdensity normal
Regression:testingfornormality
Standardize normal probability plot (pnorm) checks
for non-normality in the middle range of residuals.
Again, slightly off the line but looks ok.
pnorm e
A non-graphical test is the Shapiro-Wilk test for normality. It tests the hypothesis that the distribution is normal, in this case the
null hypothesis is that the distribution of the residuals is normal. Type
swilk e
The null hypothesis is that the distribution of the residuals is normal, here the p-value is 0.64 (way over the usual 0.05 threshold)
therefore we failed to reject the null. We conclude then that residuals are normally distributed.
PU/DSS/OTR
Regression:testingforhomoskedasticity
Another important assumption is that the variance in the residuals has to be homoskedastic, which means constant. Residuals
cannot varied for lower of higher values of X (i.e. fitted values of Y since Y=Xb). A definition:
The error term [e] is homoskedastic if the variance of the conditional distribution of [ei] given Xi [var(ei|Xi)], is constant for i=1n, and in particular
does not depend on x; otherwise, the error term is heteroskedastic (Stock and Watson, 2003, p.126)
When plotting residuals vs. predicted values (Yhat) we should not observe any pattern at all. In Stata we do this using rvfplot
right after running the regression, it will automatically draw a scatterplot between residuals and predicted values; and hettest
to produce a non-graphical test.
rvfplot, yline(0)
estat hettest
These two tests suggest the presence of heteroskedasticity in our model. The problem with this is that we may have the wrong
estimates of the standard errors for the coefficients and therefore their t-values.
By default Stata assumes homoskedastic standard errors, so we need to adjust our model to account for heteroskedasticity. To do
this we use the option robust in the regress command.
regress csat percent percent2 high, robust
See the next slide for results
PU/DSS/OTR
Regression:robuststandarderrors
To run a regression with robust standard erros type:
regress csat percent percent2 high, robust
Notice the difference in the standard errors and the t-values. Following Stock and Watson, as a ruleof-thumb, you should always assume heteroskedasticiy in your model and use robust standard errors
by adding the option robust (or r for short) to the regression command (see Stock and Watson,
2003, chapter 4)
PU/DSS/OTR
Regression:omittedvariabletest
How do we know we have included all variables we need to explain Y?
Testing for omitted variable bias is important for our model since it is related to the assumption that the
error term and the independent variables in the model are not correlated (E(e|X) = 0)
If we are missing one variable in our model and [(1)] is correlated with the included regressor; and
[(2)] the omitted variable is a determinant of the dependent variable (Stock and Watson, 2003, p.144),
then our regression coefficients are inconsistent.
In Stata we test for omitted-variable bias using the ovtest command. After running the regression
type:
ovtest
The null hypothesis is that the model does not have omitted-variables bias, the p-value is 0.2319
higher that the usual threshold of 0.05, so we fail to reject the null and conclude that we do not need
more variables.
PU/DSS/OTR
Regression:specificationerror
Anothercommandtotestmodelspecificationislinktest.Itbasicallycheckswhetherweneedmore
variablesinourmodelbyrunninganewregressionwiththeobservedY(csat)againstYhat
(csat_predicted)andYhat-squared asindependentvariables1.
Thethingtolookforhereisthesignificanceof_hatsq. The null hypothesis is that there is no
specification error. If the p-value of _hatsq is not significant then we fail to reject the null and
conclude that our model is correctly specified.
Formoredetailsseehttp://www.ats.ucla.edu/stat/stata/webbooks/reg/chapter2/statareg2.htm,and/ortypehelp linktest.
PU/DSS/OTR
Regression:outliers
To check for outliers we use the avplots command (added-variable plots). Outliers are data points
with extreme values that could have a negative effect on our estimators. After running the regression
type:
avplots
These plots regress each variable against all others, notice the coefficients on each. All data points
seem to be in range, no outliers observed.
For more details and tests on this and influential and leverage variables please check
http://www.ats.ucla.edu/stat/stata/webbooks/reg/chapter2/statareg2.htm
Also type help diagplots in the Stata command window.
PU/DSS/OTR
Regression:summaryofinfluenceindicators
DfBeta
DfFit
It is a summary measure of
leverage and high residuals.
High influence if
|DfFIT| >2*SQRT(k/N)
Covariance ratio
High impact if
|COVRATIO-1| 3*k/N
Where k is the number of
parameters (including the
intercept) and N is the sample
size.
gen cutoffdfit=
abs(dfits)>2*sqrt((e(df_m)
+1)/e(N)) & e(sample)
Regression:summaryofdistancemeasures
Cooks distance
High influence if
High influence if
D > 4/N
predict D, cooksd
Leverage
In SPSS: Analyze-Regression-Linear;
click Save. Select under Distances
to add as a new variable (COO_1) or
in syntax type
REGRESSION
/MISSING LISTWISE
/STATISTICS COEFF OUTS R
ANOVA
/CRITERIA=PIN(.05) POUT(.10)
/NOORIGIN
/DEPENDENT Y
/METHOD=ENTER X1 X2 X3
/CASEWISE PLOT(ZRESID)
OUTLIERS(3) DEFAULTS DFBETA
/SAVE MAHAL COOK LEVER
DFBETA SDBETA DFFIT SDFIT
COVRATIO.
Same as above (LEV_1)
M = leverage*(N-1)
Where N is sample size.
Sourcesforthesummarytables:
influenceindicatorsanddistancemeasures
Statnotes:
http://faculty.chass.ncsu.edu/garson/PA765/regress.htm#outlier2
AnIntroductiontoEconometricsUsingStata/ChristopherF.Baum,Stata
Press,2006
StatisticswithStata(updatedforversion9)/ LawrenceHamilton,
ThomsonBooks/Cole,2006
PU/DSS/OTR
Regression:multicollinearity
An important assumption for the multiple regression model is that independent variables are not perfectly
multicolinear. This is, one regressor should not be a linear function of another. When multicollinearity is
present, Stata will drop one of the variables to avoid a division by zero in the OLS procedure (see Stock and
Watson, 2003, chapter 5). A mayor problem with multicollinearity is that standand errors may be inflated. The
Stata command to check for multicollinearity is vif (variance inflation factor). Right after running the
regression type:
Wedonotobservemulticollinearityproblemshere.All
vifs areunder10.
Formmoredetailsseehttp://www.ats.ucla.edu/stat/stata/webbooks/reg/chapter2/statareg2.htm,and/ortypehelp vif.
PU/DSS/OTR
Regression:publishingregressionoutput(outreg2)
The command outreg2 gives you the type of presentation you see in published papers. If outreg2 is not available you need to
install it by typing
ssc install outreg2
Lets say the regression is regress csat percent percent2 high, robust
The basic syntax for outreg2 is: outreg2 using [pick a name], [type either word or excel]
After the regression type the following if you want to export the results to excel*
outreg2 using results, excel
Click here to see
the file
In excel
In word
PU/DSS/OTR
Regression:publishingregressionoutput(outreg2)
You can add more models to compare. Lets say you want to add another model without percent2:
regress csat percent high, robust
Now type to export the results to excel (notice we add the append option)
outreg2 using results, word append
In excel
In word
NOTE: If you run logit/probit regression with odds ratios you need to add the option eform to export the odd ratios
Type help outreg2 for more details. If you do not see outreg2, you may have to install it by typing ssc install outreg2. If this does not work type
findit outreg2, select from the list and click install.
Note: If you get the following error message (when you use the option append or replace it means that you need to close the excel/word window.
PU/DSS/OTR
Regression:publishingregressionoutput(outreg2)continue
Foracustomizedlook,herearesomeoptions:
***Excel
outreg2 using results, bdec(2) tdec(2) rdec(2) adec(2) alpha (0.01, 0.05, 0.10)
addstat(Adj. R-squared, e(r2_a)) excel
***Word
outreg2 using results, bdec(2) tdec(2) rdec(2) adec(2) alpha (0.01, 0.05, 0.10)
addstat(Adj. R-squared, e(r2_a)) excel
For excel
For word
Set # of
decimals for
auxiliary
statistics
Name of
the file for
the output
Click on seeout
to browse the
results
Set # of
decimals
for
coefficients
Set # of decimals
for added statistics
(addstat option)
Set # of
decimals
for the R2
Levels of
significance
PU/DSS/OTR
Regression:interactionbetweendummies
Interactiontermsareneededwheneverthereisreasontobelievethattheeffectofoneindependentvariabledependsonthevalueof
anotherindependentvariable.Wewillexploreheretheinteractionbetweentwodummy(binary)variables.Intheexamplebelow there
couldbethecasethattheeffectofstudentteacherratioontestscoresmaydependonthepercentofEnglishlearnersinthedistrict*.
Binaryhi_el,where0ifEnglishlearners(el_pct)islowerthan10%,1equalto10%orhigher
Weruntheregression
regress testscr hi_el hi_str str_el, robust
Regression:interactionbetweendummies(cont.)
Youcancomputetheexpectedvaluesoftestscoresgivendifferentvaluesofhi_str andhi_el.Toseetheeffectofhi_str given
hi_el typethefollowingrightafterrunningtheregressioninthepreviousslide.
These are different scenarios holding constant hi_el and varying
hi_str. Below we add some labels
We then obtain the average of the estimations for the test scores (for all four scenarios, notice same values for all cases).
Here we estimate the net effect of low/high student-teacher ratio holding constant the percent of
English learners. When hi_el is 0 the effect of going from low to high student-teacher ratio goes
from a score of 664.2 to 662.2, a difference of 1.9. From a policy perspective you could argue that
moving from high str to low str improve test scores by 1.9 in low English learners districts.
When hi_el is 1, the effect of going from low to high student-teacher ratio goes from a score of
645.9 down to 640.5, a decline of 5.4 points (1.9+3.5). From a policy perspective you could say
that reducing the str in districts with high percentage of English learners could improve test scores
by 5.4 points.
*ThedatausedinthissectionistheCaliforniaTestScoredataset(caschool.dta)fromchapter6ofthebookIntroductiontoEconometrics fromStockandWatson,2003.Datacanbedownloadedfrom
http://wps.aw.com/aw_stock_ie_2/50/13016/3332253.cw/index.html.Foradetaileddiscussionpleaserefertotherespectivesectioninthebook.
PU/DSS/OTR
Regression:interactionbetweenadummyandacontinuousvariable
LetsexplorethesameinteractionasbeforebutwekeepstudentteacherratiocontinuousandtheEnglishlearnersvariableasbinary.The
questionremainsthesame*.
Dependentvariable(Y) Averagetestscore,variabletestscr indataset.
Independentvariables(X)
Continuousstr,studentteacherratio.
Binaryhi_el,where0ifEnglishlearners(el_pct)islowerthan10%,1equalto10%orhigher
Interactiontermstr_el2 = str * hi_el. In Stata: generate str_el2 = str*hi_el
Wewillruntheregression
regress testscr str hi_el str_el2, robust
*ThedatausedinthissectionistheCaliforniaTestScoredataset(caschool.dta)fromchapter6ofthebookIntroductiontoEconometrics fromStockandWatson,2003.Datacanbedownloadedfrom
http://wps.aw.com/aw_stock_ie_2/50/13016/3332253.cw/index.html.Foradetaileddiscussionpleaserefertotherespectivesectioninthebook.
PU/DSS/OTR
Regression:interactionbetweentwocontinuousvariables
Letskeepnowbothvariablescontinuous.Thequestionremainsthesame*.
Dependentvariable(Y) Averagetestscore,variabletestscr indataset.
Independentvariables(X)
Continuousstr,studentteacherratio.
Continuous el_pct, percentofEnglishlearners.
Interactiontermstr_el3 = str * el_pct. In Stata: generate str_el3 = str*el_pct
Wewillruntheregression
regress testscr str el_pct str_el3, robust
Ifel_pct=10,theslopeofstris1.108
Ifel_pct=20,theslopeofstris1.096.Adifferenceineffectof0.012points.
Inthecontinuouscasethereisaneffectbutisverysmall(andnotsignificant).SeeStockandWatson,2003,forfurtherdetails.
*ThedatausedinthissectionistheCaliforniaTestScoredataset(caschool.dta)fromchapter6ofthebookIntroductiontoEconometrics fromStockandWatson,2003.Datacanbedownloadedfrom
http://wps.aw.com/aw_stock_ie_2/50/13016/3332253.cw/index.html.Foradetaileddiscussionpleaserefertotherespectivesectioninthebook.
PU/DSS/OTR
Creatingdummies
You can create dummy variables by either using recode or using a combination of tab/gen commands:
tab major, generate(major_dum)
PU/DSS/OTR
Creatingdummies(cont.)
PU/DSS/OTR
Basicdatareporting
FrequentlyusedStatacommands
Gettingonlinehelp
Statacommands
help
search
Operatingsysteminterface
pwd
cd
sysdir
mkdir
dir/ls
erase
copy
type
Usingandsavingdatafromdisk
use
clear
save
append
merge
compress
InputtingdataintoStata
input
edit
infile
infix
insheet
TheInternetandUpdatingStata
codebook
Source: http://www.ats.ucla.edu/stat/stata/notes2/commands.htm
Category
inspect
list
browse
count
assert
summarize
Table(tab)
tabulate
Datamanipulation
egen
recode
rename
drop
keep
sort
encode
decode
order
by
reshape
Formatting
format
label
Keepingtrackofyourwork
ado
news
generate
replace
update
net
describe
log
notes
Convenience
display
PU/DSS/OTR
http://www.stata.com/support/faqs/stat/panel.html
http://www.stata.com/support/faqs/stat/xtreg.html
http://www.stata.com/support/faqs/stat/xt.html
http://dss.princeton.edu/online_help/analysis/panel.htm
PU/DSS/OTR
PU/DSS/OTR
PU/DSS/OTR
Usefullinks/Recommendedbooks
DSSOnlineTrainingSectionhttp://dss.princeton.edu/training/
UCLAResourcestolearnanduseSTATAhttp://www.ats.ucla.edu/stat/stata/
DSShelpsheetsforSTATAhttp://dss/online_help/stats_packages/stata/stata.htm
IntroductiontoStata(PDF),ChristopherF.Baum,BostonCollege,USA.A67pagedescriptionofStata,itskey
featuresandbenefits,andotherusefulinformation.http://fmwww.bc.edu/GStat/docs/StataIntro.pdf
STATAFAQwebsitehttp://stata.com/support/faqs/
PrincetonDSSLibguideshttp://libguides.princeton.edu/dss
Books
Introduction to econometrics / James H. Stock, Mark W. Watson. 2nd ed., Boston: Pearson Addison
Wesley, 2007.
Data analysis using regression and multilevel/hierarchical models / Andrew Gelman, Jennifer Hill.
Cambridge ; New York : Cambridge University Press, 2007.
Econometric analysis / William H. Greene. 6th ed., Upper Saddle River, N.J. : Prentice Hall, 2008.
Designing Social Inquiry: Scientific Inference in Qualitative Research / Gary King, Robert O.
Keohane, Sidney Verba, Princeton University Press, 1994.
Unifying Political Methodology: The Likelihood Theory of Statistical Inference / Gary King, Cambridge
University Press, 1989
Statistics with Stata (updated for version 9) / Lawrence Hamilton, Thomson Books/Cole, 2006
PU/DSS/OTR