Useful Stat A Commands
Useful Stat A Commands
Simons, 29-Sep-16
Contents
Preliminaries for RPI Dot.CIO Labs........................................................................................................... 5
A. Loading Data .......................................................................................................................................... 5
A1. Memory in Stata Version 11 or Earlier ............................................................................................ 5
B. Variable Lists, If-Statements, and Options ............................................................................................ 6
C. Lowercase and Uppercase Letters .......................................................................................................... 6
D. Review Window, and Abbreviating Command Names ......................................................................... 6
E. Viewing and Summarizing Data ............................................................................................................ 6
E1. Just Looking ..................................................................................................................................... 7
E2. Mean, Variance, Number of Non-missing Observations, Minimum, Maximum, Etc. .................... 7
E3. Tabulations, Histograms, Density Function Estimates..................................................................... 7
E4. Scatter Plots and Other Plots ............................................................................................................ 7
E5. Correlations and Covariances ........................................................................................................... 8
F. Generating and Changing Variables ....................................................................................................... 8
F1. Generating Variables ........................................................................................................................ 8
F2. Missing Data ..................................................................................................................................... 8
F3. True-False Variables ......................................................................................................................... 9
F4. Random Numbers ........................................................................................................................... 10
F5. Replacing Values of Variables ....................................................................................................... 10
F6. Getting Rid of Variables ................................................................................................................. 10
F7. If-then-else Formulas ...................................................................................................................... 11
F8. Quick Calculations.......................................................................................................................... 11
F9. More................................................................................................................................................ 11
G. Means: Hypothesis Tests and Confidence Intervals ............................................................................ 11
G1. Confidence Intervals ...................................................................................................................... 11
G2. Hypothesis Tests ............................................................................................................................ 12
H. OLS Regression (and WLS and GLS) ................................................................................................. 12
H1. Variable Lists with Automated Category Dummies and Interactions ........................................... 12
H2. Improved Robust Standard Errors in Finite Samples..................................................................... 13
H3. Weighted Least Squares ................................................................................................................. 13
H4. Feasible Generalized Least Squares ............................................................................................... 14
I. Post-Estimation Commands .................................................................................................................. 14
I1. Fitted Values, Residuals, and Related Plots .................................................................................... 14
I2. Confidence Intervals and Hypothesis Tests..................................................................................... 14
I3. Nonlinear Hypothesis Tests ............................................................................................................. 15
I4. Computing Estimated Expected Values for the Dependent Variable.............................................. 15
I5. Displaying Adjusted R2 and Other Estimation Results ................................................................... 16
I6. Plotting Any Mathematical Function .............................................................................................. 16
I7. Influence Statistics ........................................................................................................................... 17
I8. Functional Form Test....................................................................................................................... 17
I9. Heteroskedasticity Tests .................................................................................................................. 17
I10. Serial Correlation Tests ................................................................................................................. 18
I11. Variance Inflation Factors ............................................................................................................. 18
I12. Marginal Effects ............................................................................................................................ 18
J. Tables of Regression Results ................................................................................................................ 19
J0. Copying and Pasting from Stata to a Word Processor or Spreadsheet Program ............................. 19
J1. Tables of Regression Results Using Statas Built-In Commands ................................................... 19
J2. Tables of Regression Results Using Add-On Commands............................................................... 20
J2a. Installing or Accessing the Add-On Commands ....................................................................... 20
J2b. Storing Results and Making Tables........................................................................................... 21
J2c. Near-Publication-Quality Tables ............................................................................................... 21
J2d. Understanding the Table Commands Options ......................................................................... 22
J2e. Saving Tables as Files ............................................................................................................... 22
J2f. Wide Tables ............................................................................................................................... 23
J2g. Storing Additional Results ........................................................................................................ 23
J2h. Clearing Stored Results ............................................................................................................. 23
J2i. More Options and Related Commands ...................................................................................... 23
J3. Tabulations and General Tables Using Add-On Commands .......................................................... 23
K. Data Types, When 3.3 3.3, and Missing Values ............................................................................... 24
L. Results Returned after Commands ....................................................................................................... 24
M. Do-Files and Programs ........................................................................................................................ 24
N. Monte-Carlo Simulations ..................................................................................................................... 26
O. Doing Things Once for Each Group .................................................................................................... 26
P. Generating Variables for Time-Series and Panel Data ......................................................................... 27
P1. Creating a Time Variable................................................................................................................ 27
P1a. Time Variable that Starts from a First Time and Increases by 1 at Each Observation ............. 27
P1b. Time Variable from a Date String ............................................................................................ 28
P1c. Time Variable from Multiple (e.g., Year and Month) Variables .............................................. 28
P1d. Time Variable Representation in Stata ..................................................................................... 29
P2. Telling Stata You Have Time Series or Panel Data ....................................................................... 29
P3. Lags, Forward Leads, and Differences ........................................................................................... 29
P4. Generating Means and Other Statistics by Individual, Year, or Group .......................................... 30
Q. Panel Data Statistical Methods ............................................................................................................ 30
Q1. Fixed Effects Using Dummy Variables ...................................................................................... 30
Q2. Fixed Effects De-Meaning .......................................................................................................... 31
Q3. Other Panel Data Estimators .......................................................................................................... 31
Q4. Time-Series Plots for Multiple Individuals.................................................................................... 32
R. Probit and Logit Models....................................................................................................................... 32
R1. Interpreting Coefficients in Probit and Logit Models .................................................................... 32
S. Other Models for Limited Dependent Variables .................................................................................. 34
S1. Censored and Truncated Regressions with Normally Distributed Errors ...................................... 35
S2. Count Data Models ......................................................................................................................... 35
S3. Survival Models (a.k.a. Hazard Models, Duration Models, Failure Time Models) ....................... 35
T. Instrumental Variables Regression ....................................................................................................... 36
T1. GMM Instrumental Variables Regression ...................................................................................... 37
T2. Other Instrumental Variables Models ............................................................................................ 38
U. Time Series Models ............................................................................................................................. 38
U1. Autocorrelations ............................................................................................................................. 38
U2. Autoregressions (AR) and Autoregressive Distributed Lag (ADL) Models ................................. 38
U3. Information Criteria for Lag Length Selection .............................................................................. 39
U4. Augmented Dickey Fuller Tests for Unit Roots ............................................................................ 39
3
Opens the data editor, to type in or paste data. You must close the
data editor before you can run any further commands.
use "filename.dta"
Reads in a Stata-format data file.
insheet delimited "filename.txt"
Reads in text data (allowing for various text encodings), in Stata 14
or newer.
insheet using "filename.txt"
Old way to read text data, faster for plain English-language text.
import excel "filename.xlsx", firstrow Reads data from an Excel files first worksheet, treating the first
row as variable names.
import excel "filename.xlsx", sheet("price data") firstrow Reads data from the worksheet named price
data in an Excel file, treating the first row as variable names.
save "filename.dta"
Saves the data.
Before you load or save files, you may need to change to the right directory. Under the File menu,
choose Change Working Directory, or use Statas cd command.
A1. Memory in Stata Version 11 or Earlier
As of this writing, Stata is in version 14. If you are using Stata version 11 or earlier, and you
will read in a big dataset, then before reading in your data you must tell Stata to make available
enough computer memory for your data. For example:
set memory 100m
Sets memory available for data to 100 megabytes. Clear before setting.
If you get a message while using Stata 11 or earlier that there is not enough memory, then clear
the existing data (with the clear command), set the memory to a large enough amount, and then
re-do your analyses as necessary you should be saving your work in a do file, as noted below in
section M).
B. Variable Lists, If-Statements, and Options
Most commands in Stata allow (1) a list of variables, (2) an if-statement, and (3) options.
1. A list of variables consists of the names of the variables, separated with spaces. It goes immediately
after the command. If you leave the list blank, Stata assumes where possible that you mean all
variables. You can use an asterisk as a wildcard (see Statas help for varlist). Examples:
edit var1 var2 var3
Opens the data editor, just with variables var1, var2, and var3.
edit
Opens the data editor, with all variables.
In later examples, varlist means a list of variables, and varname (or yvar etc.) means one variable.
2. An if-statement restricts the command to certain observations. You can also use an in-statement. Ifand in-statements come after the list of variables. Examples:
edit var1 if var2 > 3
Opens the data editor, just with variable var1, only for observations in
which var2 is greater than 3.
edit if var2 == var3
Opens the data editor, with all variables, only for observations in which
var2 equals var3.
edit var1 in 10
Opens the data editor, just with var1, just in the 10th observation.
edit var1 in 101/200
Opens the data editor, just with var1, in observations 101-200.
edit var1 if var2 > 3 in 101/200 Opens the data editor, just with var1, in the subset of
observations 101-200 that meet the requirement var2 > 3.
3. Options alter what the command does. There are many options, depending on the command get
help on the command to see a list of options. Options go after any variable list and if-statements,
and must be preceded by a comma. Do not use an additional comma for additional options (the
comma works like a toggle switch, so a second comma turns off the use of options!). Examples:
use "filename.dta", clear Reads in a Stata-format data file, clearing all data previously in memory!
(Without the clear option, Stata refuses to let you load new data if
you havent saved the old data. Here the old data are forgotten and
will be gone forever unless you saved some version of them.)
save "filename.dta", replace Saves the data, replacing a previously-existing file if any.
You will see more examples of options below.
C. Lowercase and Uppercase Letters
Case matters: if you use an uppercase letter where a lowercase letter belongs, or vice versa, an error
message will display.
D. Review Window, and Abbreviating Command Names
The Review window lists commands you typed previously. Click in the Review window to put a
previous command in the Command window (then you can edit it as desired). Double-click to run a
command. Another shortcut is that many commands can have their names abbreviated. For example
below instead of typing summarize, su will do, and instead of regress, reg will do.
E. Viewing and Summarizing Data
Here, remember two points from above: (1) leave a varlist blank to mean all variables, and (2) you can
use if-statements to restrict the observations used by each command.
and choose Stata Command, type graph_intro, and press return. Scroll down past the table
of contents and read the section labeled A quick tour.
E5. Correlations and Covariances
The following commands compute the correlations and covariances between any list of
variables. Note that if any of the variables listed have missing values in some rows, those rows are
ignored in all calculations.
correlate var1 var2
Computes the sample correlations between variables.
correlate var1 var2 , covariance Computes the sample covariances between variables.
Sometimes you have missing values in some rows, but want to use all available data wherever
possible i.e., for some correlations but not others. For example, if you have data on health,
nutrition, and income, and income data are missing for 90% of your observations, then you could
compute the correlation of health with nutrition using all of the observations, while computing the
correlations of health with income and of nutrition with income for just the 10% of observations
that have income data. These are called pairwise correlations and can be obtained as follows:
pwcorr var1 var2
Computes pairwise sample correlations between variables.
F. Generating and Changing Variables
A variable in Stata is a whole column of data. You can generate a new column of data using a formula,
and you can replace existing values with new ones. Each time you do this, the calculation is done
separately for every observation in the sample, using the same formula each time.
F1. Generating Variables
generate newvar =
Generate a new variable using the formula you enter in place of .
Examples follow.
gen f = m * a
Remember, Stata allows abbreviations: gen means generate.
gen xsquared = x^2
gen logincome = log(income) Use log() or ln() for a log-base-e, or log10() for log-base-10.
gen q = exp(z) / (1 exp(z))
gen a = abs(cos(x))
This uses functions for absolute value, abs(), and cosine, cos(). Many
more functions are available get help for functions for a list.
F2. Missing Data
Be aware of missing data in Stata. Missing data can result when you compute a number whose
answer is not defined; for example, if you use gen logincome = log(income) then logincome will
be missing for any observation in which income is zero or negative. Missing data can also result
during data collection; for example, in data on publicly listed companies often R&D expenditures
data are unavailable.
Missing data can be entered in Stata by using a period instead of a number. When you list data, a
period likewise indicates a missing datum.
Missing data can be used in Stata calculations. For example, you can check whether logincome
is missing, and only list the data for observations where this is true:
list if logincome==.
List only observations in which logincome is missing.
A missing datum counts as infinity when making comparisons. For example, if logincome is not
missing, then it is less than infinity, so you could create a variable that tells whether logincome is
non-missing by checking whether logincome is less the missing value code:
Calculate the formula you type in, and display the result. Examples
follow.
display (52.3-10.0)/12.7
display normal(1.96)
Compute the probability to the left of 1.96 using the cumulative standard
normal distribution.
display F(10,9000,2.32) Compute the probability that an F-distributed number, with 10 and 9000
degrees of freedom, is less than or equal to 2.32. Also, there is a
function Ftail(n1,n2,f) = 1 F(n1,n2,f). Similarly, you can use
ttail(n,t) for the probability that T>t, for a t-distributed random
variable T with n degrees of freedom.
F9. More
For functions available in equations in Stata, use Statas Help menu, choose Stata Command,
and enter functions. To generate variables separately for different groups of observations, see
the commands in sections O and P4. For time-series and panel data, see section P, especially the
notations for lags, leads, and differences in section P3. If you need to refer to a specific
observation number, use a reference like x[3], meaning the valuable of the variable x in the 3rd
observation. In Stata _n means the current observation (when using generate or replace), so that
for example x[_n-1] means the value of x in the preceding observation, and _N means the
number of observations, so that x[_N] means the value of x in the last observation.
G. Means: Hypothesis Tests and Confidence Intervals
G1. Confidence Intervals
In Stata version 13 or earlier, omit the word means below.
ci means varname
Confidence interval for the mean of varname (using asymptotic normal
distribution).
ci means varname, level(#) Confidence interval at #%. For example, use 99 for a 99%
confidence interval.
by varlist: ci means varname Compute confidence intervals separately for each unique set of
values of the variables in varlist.
by female: ci means workhours Compute confidence intervals for the mean of workhours,
separately for people who are males versus females.
11
Other commands also report confidence intervals, and may be preferable because they do more,
such as computing a confidence interval for the difference in means between by groups (e.g.,
between men and women). See section G2. (Also, Statas mean command reports confidence
intervals.)
G2. Hypothesis Tests
ttest varname == #
Test the hypothesis that the mean of a variable is equal to some number,
which you type instead of the number sign #.
ttest varname1 == varname2 Test the hypothesis that the mean of one variable equals the mean of
another variable.
ttest varname, by(groupvar) Test the hypothesis that the mean of a single variable is the same for
all groups. The groupvar must be a variable with a distinct value for
each group. For example, groupvar might be year, to see if the mean
of a variable is the same in every year of data.
H. OLS Regression (and WLS and GLS)
regress yvar xvarlist
Regress the dependent variable yvar on the independent variables
xvarlist. For example: regress y x, or regress y x1 x2 x3.
regress yvar xvarlist, vce(robust) Regress, but this time compute robust (Eicker-Huber-White)
standard errors. We are always using the vce(robust) option in
ECON-4570 Econometrics, because we want consistent (i.e,,
asymptotically unbiased) results, but we do not want to have to
assume homoskedasticity and normality of the random error terms.
So if you are in ECON-4570 Econometrics, remember always to
specify the vce(robust) option after estimation commands. The
vce stands for variance-covariance estimates (of the estimated
model parameters).
regress yvar xvarlist, vce(robust) level(#) Regress with robust standard errors, and this time change the
confidence interval to #% (e.g. use 99 for a 99% confidence
interval).
Occasionally you will need to regress without vce(robust), to allow post-regression tests that assume
homoscedasticity. Notably, Stata displays adjusted R2 values only under the assumption of
homoscedasticity, since the usual interpretation of R2 presumes homoscedasticity. However, another
way to see the adjusted R2 after using regress, vce(robust) is to type display e(r2_a); see section
I5.
H1. Variable Lists with Automated Category Dummies and Interactions
Stata (beginning with Stata 11) allows you enter variable lists that automatically create dummies
for categories as well as interaction variables. For example, suppose you have a variable named
usstate numbered 1 through 50 for the fifty U.S. states, and you want to include forty-nine 0-1
dummy variables that allow for differences between the first state (Alabama, say) and other states.
Then you could simply include i.usstate in the xvarlist for your regression. Similarly, suppose you
want to create the interaction between two variables, named age (a continuous variable) and male
(a 0-1 dummy variable). Then, including c.age#i.male includes the interaction (the multiple of the
two variables) in the regression. The c. in front of age indicates that it is a continuous variable,
whereas the i. in front of male indicates that it is a 0-1 dummy variable. Including
c.age#i.usstate adds 49 variables to the model, age times each of the 49 state dummies. Use ##
12
instead of # to add full interactions, for example c.age##i.male means age, male, and agemale.
Similarly, c.age##i.usstate means age, 49 state dummies, and 49 state dummies multiplied by age.
You can use # to create polynomials. For example, age age#age age#age#age is a thirdorder polynomial, with variables age and age2 and age3. Having done this, you can use Statas
margins command to compute marginal effects: the average value of the derivatives d(y)/d(age)
across all observations in the sample. This works even if your regression equation includes
interactions of age with other variables.
Here are some examples using automated category dummies and interactions, termed factor
variables in the Stata manuals (see the Users Guide U11.4 for more information):
reg yvar x1 i.x2, vce(robust) Includes a 0-1 dummy variables for the groups indicated by unique
values of variable x2.
reg wage c.age i.male c.age#i.male, vce(robust)
Regress wage on age, male, and agemale.
reg wage c.age##i.male, vce(robust) Regress wage on age, male, and agemale.
reg wage c.age##i.male c.age#c.age, vce(robust) Regress wage on age, male, agemale, and age2.
reg wage c.age##i.male c.age#c.age c.age#c.age#i.male, vce(robust) Regress wage on age, male,
agemale, age2, and age2male.
reg wage c.age##i.usstate c.age#c.age c.age#c.age#i.usstate, vce(robust) Regress wage on age,
49 state dummies, 49 variable that are agestatedummyk, age2, and
49 variable that are age2statedummyk (k=1,,49).
Speed Tip: Dont generate lots of dummy variables and interactions instead use this factor
notation to compute your dummy variables and interactions on the fly during statistical
estimation. This usually is much faster and saves lots of memory, if you have a really big dataset.
H2. Improved Robust Standard Errors in Finite Samples
For robust standard errors, an apparent improvement is possible. Davidson and MacKinnon*
report two variance-covariance estimation methods that seem, at least in their Monte Carlo
simulations, to converge more quickly, as sample size n increases, to the correct variancecovariance estimates. Thus their methods seem better, although they require more computational
time. Stata by default makes Davidson and MacKinnons recommended simple degrees of
freedom correction by multiplying the estimated variance matrix by n/(n-K). However, students in
ECON-6570 Advanced Econometrics learn about an alternative in which the squared residuals are
rescaled. To use this formula, specify vce(hc2) instead of vce(robust), to use the approach
discussed in Hayashi p. 125 formula 2.5.5 using d=1 (or in Greenes text, 6th edition, on p. 164).
An alternative is vce(hc3) instead of vce(robust) (Hayashi page 125 formula 2.5.5 using d=2
or Greene p. 164 footnote 15).
H3. Weighted Least Squares
Students in ECON-6570 Advanced Econometrics learn about (variance-)weighted least squares. If
you know (to within a constant multiple) the variances of the error terms for all observations, this
yields more efficient estimates (OLS with robust standard errors works properly using asymptotic
methods but is not the most efficient estimator). Suppose you have, stored in a variable sdvar, a
reasonable estimate of the standard deviation of the error term for each observation. Then
weighted least squares can be performed as follows:
*
R. Davidson and J. MacKinnon, Estimation and Inference in Econometrics, Oxford: Oxford University
Press, 1993, section 16.3.
13
However, you may need to carry out F-tests, as well as compute confidence intervals and t-tests for
linear combinations of coefficients in the model. Here are example commands. Note that when
a variable name is used in this subsection, it really refers to the coefficient (the k) in front of that
variable in the model equation.
lincom logpl+logpk+logpf Compute the estimated sum of three model coefficients, which are the
coefficients in front of the variables named logpl, logpk, and logpf.
Along with this estimated sum, carry out a t-test with the null
hypothesis being that the linear combination equals zero, and
compute a confidence interval.
lincom 2*logpl+1*logpk-1*logpf Like the above, but now the formula is a different linear
combination of regression coefficients.
lincom 2*logpl+1*logpk-1*logpf, level(#) As above, but this time change the confidence interval
to #% (e.g. use 99 for a 99% confidence interval).
test logpl+logpk+logpf==1 Test the null hypothesis that the sum of the coefficients of variables
logpl, logpk, and logpf, totals to 1. This only makes sense after a
regression involving variables with these names. After OLS
regression, this is an F-test. More generally, it is a Wald test.
test (logq2==logq1) (logq3==logq1) (logq4==logq1) (logq5==logq1) Test the null hypothesis
that four equations are all true simultaneously: the coefficient of
logq2 equals the coefficient of logq1, the coefficient of logq3 equals
the coefficient of logq1, the coefficient of logq4 equals the
coefficient of logq1, and the coefficient of logq5 equals the
coefficient of logq1; i.e., they are all equal to each other. After OLS
regression, this is an F-test. More generally, it is a Wald test.
test x3 x4 x5
Test the null hypothesis that the coefficient of x3 equals 0 and the
coefficient of x4 equals 0 and the coefficient of x5 equals 0. After
OLS regression, this is an F-test. More generally, it is a Wald test.
I3. Nonlinear Hypothesis Tests
Students in ECON-6570 Advanced Econometrics learn about nonlinear hypothesis tests. After
estimating a model, you could do something like the following:
testnl _b[popdensity]*_b[landarea] = 3000
Test a nonlinear hypothesis. Note that coefficients
must be specified using _b, whereas the linear test command lets
you omit the _b[].
testnl (_b[mpg] = 1/_b[weight]) (_b[trunk] = 1/_b[length]) For multi-equation tests you can put
parentheses around each equation (or use multiple equality signs in
the same equation; see the Stata manual, [R] testnl, for examples).
I4. Computing Estimated Expected Values for the Dependent Variable
di _b[xvarname]
Display the value of an estimated coefficient after a regression. Use the
variable name _cons for the estimated constant term. Of course
theres no need just to display these numbers, but the good thing is
that you can use them in formulae. See the next example.
di _b[_cons] + _b[age]*25 + _b[female]*1 After a regression of y on age and female (but no
other independent variables), compute the estimated value of y for a
25-year-old female. See also the predict command mentioned above
in section I1, and the margins command.
15
other heteroskedasticity tests that may be more appropriate. Statas imtest command also carries
out other tests, and the commands hettest and szroeter carry out different tests for
heteroskedasticity.
The Breusch-Pagan Lagrange multiplier test, which assumes normally distributed errors, can be
carried out after running a regression, by using the command:
estat hettest, normal
Heteroskedasticity test - Breusch-Pagan Lagrange mulitplier.
Other tests that do not require normally distributed errors include:
estat hettest, iid
Heteroskedasticity test Koenkers (1981)s score test, assumes iid
errors.
estat hettest, fstat
Heteroskedasticity test Wooldridges (2006) F-test, assumes iid errors.
estat szroeter, rhs mtest(bonf) Heteroskedasticity test Szroeter (1978) rank test for null
hypothesis that variance of error term is unrelated to each variable.
estat imtest
Heteroskedasticity test Cameron and Trivedi (1990), also includes
tests for higher-order moments of residuals (skewness and kurtosis).
For further information see the Stata manuals.
See also the ivhettest command described in section T1 of this document. This makes available
the Pagan-Hall test which has advantages over the results from estat imtest.
I10. Serial Correlation Tests
Students in ECON-6570 Advanced Econometrics learn about tests for serial correlation. To carry
out these tests in Stata, you must first tsset your data as described in section P of this document
(see also section U). For a Breusch-Godfrey test where, say, p = 3, do your regression and then
use Statas estat bgodfrey command:
estat bgodfrey, lags(1 2 3) Heteroskedasticity tests including White test.
Other tests for serial correlation are available. For example, the Durbin-Watson d-statistic is
available using Statas estat dwatson command. However, as Hayashi (p. 45) points out, the
Durbin-Watson statistic assumes there is no endogeneity even under the alternative hypothesis, an
assumption which is typically violated if there is serial correlation, so you really should use the
Breusch-Godfrey test instead (or use Durbins alternative test, estat durbinalt). For the BoxPierce Q in Hayashis 2.10.4 or the modified Box-Pierce Q in Hayashis 2.10.20, you would need
to compute them using matrices. The Ljung-Box test is available in Stata by using the command:
wntestq varname, lags(#) Ljung-Box portmanteau (Q) test for white noise.
I11. Variance Inflation Factors
Students in ECON-6570 Advanced Econometrics may use variance inflation factors (VIFs), which
show the multiple by which the estimated variance of each coefficient estimate is larger because of
non-orthogonality with other variables in the model. To compute the VIFs, use:
estat vif
After a regression, display variance inflation factors.
I12. Marginal Effects
After using regress or almost any other estimation command, you can compute marginal effects
using the margins command (available beginning in Stata 11). Marginal effects are d(y)/d(xk)
for continuous variables xk, or delta-y/delta-xk for discrete variables xk. In particular, these are
reported for the average individual in the sample. Use factor variables when writing the list of
variables in the model, so that Stata knows the way in which each variable contributes to the model
see section H1 above. Here is a simple example, but you should read the Stata manual entry [R]
margins if you plan to use the margins command much.
18
margins age
a folder named stata extensions. You merely need to tell Stata where to look (you could copy
the relevant files anywhere, and just tell Stata where). Type the command listed below in Stata.
You only need to run this command once after you start or restart Stata. Put the command at the
beginning of your do-files (you also may need to include the command eststo clear to avoid any
confusion with previous results see section J2h).
adopath + folderToLookIn
Here, replace folderToLookIn with the name of the folder, by using one of the following two
commands (the first for ECON-4570 or -6560, the second for ECON-6570):
adopath + "//hass11.win.rpi.edu/classes/ECON-4570-6560/stata extensions"
adopath + "//hass11.win.rpi.edu/classes/ECON-6570/stata extensions"
(Note the use of forward slashes above instead of the Windows standard of backslashes for file
paths. If you use backslashes, you will probably need to use four backslashes instead of two at the
front of the file path. Why? In certain settings, including in do-files, Stata converts two
backslashes in a row into just one for Stata \$ means $, \` means `, and \\ means \, in order to
provide a way to tell Stata that a dollar sign is not the start of a global macro but is just a dollar
sign, or a backquote is not the start of a local macro but is just a backquote. (A local macro is
Statas name for a local variable in a program or do-file, and a global macro is Statas name for a
global variable in a program or do-file.))
J2b. Storing Results and Making Tables
Once this is done, you can store results more simply, store additional results not saved by Statas
built-in commands, and create tables that report information not allowed using Statas built-in
commands.
eststo: reg y x1 x2, vce(robust) Regress y on x1 and x2 (with robust standard errors) and store
the results. Estimation results will be stored with names like est1,
est2, etc. the name will be printed out after each command.
eststo modelname: reg y x1 x2, vce(robust) Same as above, but you choose the name to use when
storing results, instead of just using est1, etc. The modelname
could be for example myreg1 (begin your names with a letter, after
which you can use letters, digits 0 through 9, or underscores _ up to
32 total characters).
eststo: quietly reg y x1 x2 x3, vce(robust) Similar to above, but quietly tells Stata not to
display any output.
J2c. Near-Publication-Quality Tables
Here is how to make a near-publication-quality table. In place of the est1 est2 below, type the
names of the stored estimates that you want in the table.
esttab est1 est2, b(a3) se(a3) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) r2(3) ar2(3) scalars(F) nogaps
Make a near-publication-quality table. You will still need to make
the variable names more meaningful, change the column headings,
and set up the borders appropriately.
Here is how to save that table in a file that you can open in Word. Put using filename just
before the comma in the above command, and add the rtf option after the comma. Make sure
you change directory first, so the file will save in the right folder. To change directory, under the
File menu, choose Change Working Directory, or use Statas cd command.
21
using mytable, rtf b(a3) se(a3) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) r2(3) ar2(3) scalars(F) nogaps
Save a near-publication-quality table, putting it in a rich text file
(mytable.rtf) that can be opened by Word.
22
23
document mainly assumes you are used to the do-file editor, but below are two notes on using and
writing do-files, plus an example of how to write a program.
At the top of the do-file editor are icons for various purposes. Move the mouse over each icon to
display what it does. The set of icons varies across computer types and versions of Stata, but might
include: new do-file, open do-file, save, print, find in this do-file, show white-space symbols, cut, copy,
paste, undo, redo, preview in viewer, run, and do. The preview in viewer icon you wont need (its
useful when writing documents such as help files for Statas viewer). The do icon, at the right, is most
important. Click on it to do all of the commands in the do-file editor: the commands will be sent to
Stata in the order listed. However, if you have selected some text in the do-file editor, then only the
lines of text you selected will be done, instead of all of the text. (If you select part of a line, the whole
line will still be done.) The run icon has the same effect, except that no output is printed in Statas
results window. Since you will want to see what is happening, you should use the do icon not the
run icon.
You will want to include comments in the do-file editor, so you remember what your do-files were
for. There are three ways to include comments: (1) put an asterisk at the beginning of a line (it is okay
to have white space, i.e., spaces and tabs, before the asterisk) to make the line a comment; (2) put a
double slash // anywhere in a line to make the rest of the line a comment; (3) put a /* at the
beginning of a comment and end it with */ to make anything in between a comment, even if it spans
multiple lines. For example, your do-file might look like this:
* My analysis of employee earnings data.
* Since the data are used in several weeks of the course, the do-file saves work for later use!
clear // This gets rid of any pre-existing data!
adopath + "//hass11.win.rpi.edu/classes/ECON-4570/stata extensions" // If you're in ECON-4570.
use "L:\myfolder\myfile.dta"
* I commented out the following three lines since I'm not using them now:
/* regress income age, vce(robust)
predict incomeHat
scatter incomeHat income age */
* Now do my polynomial age analyses:
gen age2 = age^2
gen age3 = age^3
eststo p3: regress income age age2 age3 bachelor, vce(robust)
eststo p2: regress income age age2 bachelor, vce(robust)
esttab p3 p2, b(a3) se(a3) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) r2(3) ar2(3) scalars(F) nogaps
You can write programs in the do-file editor, and sometimes these are useful for repetitive tasks.
Here is a program to create some random data and compute the mean.
capture program drop randomMean
Drops the program if it exists already.
program define randomMean, rclass
Begins the program, which is rclass.
drop _all
Drops all variables.
quietly set obs 30
Use 30 observations, and dont say so.
gen r = uniform()
Generate random numbers.
summarize r
Compute mean.
return scalar average = r(mean)
Return it in r(average).
end
Note above that rclass means the program can return a result. After doing this code in the do-file, you
can use the program in Stata. Be careful, as it will drop all of your data! It will then generate 30
25
uniformly-distributed random numbers, summarize them, and return the average. (By the way, you can
make the program work faster by using the meanonly option after the summarize command above,
although then the program will not display any output.)
N. Monte-Carlo Simulations
It would be nice to know how well our statistical methods work in practice. Often the only way to know
is to simulate what happens when we get some random data and apply our statistical methods. We do
this many times and see how close our estimator is to being unbiased, normally distributed, etc. (Our
OLS estimators will do better with larger sample sizes, when the x-variables are independent and have
larger variance, and when the random error terms are closer to normally distributed and have smaller
variance.) Here is a Stata command to call the above (at the end of section M) program 100,000 times
and record the result from each time.
simulate "randomMean" avg=r(average), reps(100000)
The result will be a dataset containing one variable, named avg, with 100,000 observations. Then you
can check the mean and distribution of the randomly generated sample averages, to see whether they
seem to be nearly unbiased and nearly normally distributed.
summarize avg
kdensity avg , normal
Unbiased means right on average. Since the sample mean, of say 30 independent draws of a random
variable, has been proven to give an unbiased estimate of the variables true population mean, you had
better find that the average (across all 100,000 experiments) result computed here is very close to the
true population mean. And the central limit theorem tells you that as a sample size gets larger, in this
case reaching the not-so-enormous size of 30 observations, the means you compute should have a
probability distribution that is getting close to normally distributed. By plotting the results from the
100,000 experiments, you can see how close to normally-distributed the sample mean is. Of course, we
would get slightly different results if we did another set of 100,000 random trials, and it is best to use as
many trials as possible to get exactly the right answer we would need to do an infinite number of such
experiments.
Try similar simulations to check results of OLS regressions. You will need to change the program in
section M and alter the simulate command above. One approach is to change the program in section
M to return results named b0, b1, b2, etc., by setting them equal to the coefficient estimates
_b[varname], and then alter the simulate command above to use the regression coefficient estimates
instead of the mean (you might say b0=r(b0) b1=r(b1) b2=r(b2) in place of avg=r(average)). An
easier approach, though, is to get rid of the , rclass in the program at the end of section M, and just do
the regression in the program the regression command itself will return results that you can use; your
simulate command might then be something like simulate "randomReg" b0=_b[_cons] b1=_b[x1]
b2=_b[x2], reps(1000).
O. Doing Things Once for Each Group
Statas by command lets you do something once for each of a number of groups. Data must be sorted
first by the groups. For example:
sort year
Sort the data by year.
by year: regress income age, vce(robust) Regress separately for each year of data.
sort year state
Sort the data by year, and within that by state.
by year state: regress income age, vce(robust) Regress separately for each state and year
combination.
26
Sometimes, when there are a lot of groups, you dont want Stata to display the output. The quietly
command has Stata take action without showing the output:
quietly by year: generate xInFirstObservationOfYear = x[1] The x[1] means look at the first
observation of x within each particular by-group.
quietly by year (dayofyear): generate xInFirstObservationOfYear = x[1] In the above command,
a problem is that you might accidentally have the data sorted the
wrong way within each year. Listing more variables in parentheses
after the year requires that within each year, the data must be sorted
correctly by the other variables. This doesnt do the sorting for you,
but it ensures the sort order is correct. That way you know what
youll get when you refer to the first observation of the year.
quietly bysort year (dayofyear): generate xInFirstObservationOfYear = x[1] This is the same as
above, but the bysort command sorts as requested before doing the
command for each by-group.
qby year (dayofyear): generate xInFirstObservationOfYear = x[1] qby is shorthand for quietly
by.
qbys year (dayofyear): generate xInFirstObservationOfYear = x[1] qbys is shorthand for
quietly bysort.
See also section P4 for more ways to generate results, e.g., means or standard deviations, separately for
each by-group.
Power User Tip: Master these commands for by-groups to help make yourself a data preparation
whiz. Also master the egen command (see section P4).
P. Generating Variables for Time-Series and Panel Data
With panel and time series data, you may need to (1) create a time variable; (2) tell Stata what variable
measures time (and for panel data what variable distinguishes individuals in the sample); (3) use lags,
leads, and differences; and (4) generate values separately for each individual in the sample. Here are
some commands to help you.
P1. Creating a Time Variable
You need a time variable that tells the year, quarter, month, day, second, or whatever unit of time
corresponds to each observation. A common problem is to convert data from some other format,
like a month-day-year string, or numeric values for quarter and year, into a single time variable.
Stata has lots of tools to help, as documented in Statas help for datetime. Some common
methods are listed below.
Your time variable should be an integer, and should not usually have gaps between numbers.
For example, it is okay to have years in the data be 1970, 1971, , 2006, but if your time variable
is every other year, e.g., 1970, 1972, 1974, , then you should create a new variable like time =
(year-1970)/2. Stata has lots of options and commands to help with setting up quarterly data, etc.
The following is (as always in this document) just a start.
P1a. Time Variable that Starts from a First Time and Increases by 1 at Each Observation
If you have not yet created a time variable, and your data are in order and do not have gaps, you
might create a year, quarter, or day variable as follows:
generate year = 1900 + _n - 1 Create a new variable that specifies the year, beginning with 1900
in the first observation and increasing by 1 thereafter. Be sure your
data are sorted in the right order first.
27
generate quarter = tq(1970q1) + _n - 1 Create a new variable that specifies the time, beginning
with 1970 quarter 1 in the first observation, and increasing by 1
quarter in each observation. Be sure your data are sorted in the right
order first. The result is an integer number increasing by 1 for each
quarter (1960 quarter 2 is specified as 1, 1960 quarter 3 is specified
as 2, etc.).
format quarter %tq
Tell Stata to display values of quarter as quarters.
generate day = td(01jan1960) + _n - 1 Create a new variable that specifies the time, beginning
with 1 Jan. 1960 in the first observation, and increasing by 1 day in
each observation. Be sure your data are sorted in the right order
first. The result is an integer number increasing by 1 for each day
(01jan1960 is specified as 0, 02 jan1960 is specified as 2, etc.).
format day %td
Tell Stata to display values of day as dates.
Like the td() and tq() functions used above, you may also use tw() for week, tm() for
month, or th() for half-year. For more information, get help on functions and look under
time-series functions.
P1b. Time Variable from a Date String
If you have a string variable that describes the date for each observation, and you want to convert it
to a numeric date, you can probably use Statas very flexible date conversion functions. You will
also want to format the new variable appropriately. Here are some examples:
gen t = daily(dstr, "mdy") Generate a variable t, starting from a variable dstr that contains dates
like Dec-1-2003, 12-1-2003, 12/1/2003, January 1, 2003,
jan1-2003, etc. Note the "mdy", which tells Stata the ordering of
the month, day, and year in the variable. If the order were year,
month, day, you would use "ymd".
format t %td
This tells Stata the variable is a date number that specifies a day.
Like the daily() function used above, The similar functions monthly(strvar, "ym") or
monthly(strvar, "my"), and quarterly(strvar, "yq") or quarterly(strvar, "qy"), allow monthly or
quarterly date formats. Use %tm or %tq, respectively, with the format command. These date
functions require a way to separate the parts. Dates like 20050421 are not allowed. If d1 is a
string variable with such dates, you could create dates with separators in a new variable d2 suitable
for daily(), like this:
gen str10 d2 = substr(d1, 1, 4) +"-" + substr(d1, 5, 2) +"-" + substr(d1, 7, 2) This uses the
substr() function, which returns a substring the part of a string
beginning at the first numbers character for a length given by the
second number.
P1c. Time Variable from Multiple (e.g., Year and Month) Variables
What if you have a year variable and a month variable and need to create a single time variable?
Or what if you have some other set of time-period numbers and need to create a single time
variable? Stata has functions to build the time variable from its components:
gen t = ym(year, month) Create a single time variable t from separate year (the full 4-digit year)
and month (1 through 12) variables.
format t %tm
This tells Stata to display the variables values in a human-readable
format like 2012m5 (meaning May 2012).
Other functions are available for other periods:
28
*For data in milliseconds, data must be stored in double-precision number format (see section K
above), using gen double t = mdyhms(month, day, year, hour, minute, second). For any of the
other periodicities above, you can use long or double data types to store a broader range of
numbers than is possible using the default float data type. For data in milliseconds, a version
accounting for leap seconds uses Cmdyhms(month, day, year, hour, minute, second) and %tC.
If your data do not match one of these standard periodicities, you can create your own time
variable as in section P1a, but without using the format command to specify a human-readable
format (the time numbers will just display as the numbers they are).
P1d. Time Variable Representation in Stata
If you use one of these standard Stata date formats, formatting your numbers with a Stata format
such as %tq or %td, then Stata is storing the information as ordinary numbers and has picked the
number 0 (zero) to correspond to some particular time. For example, in daily format, 0 means the
first day of January in 1960, 1 means the second day of January 1960, -1 means the last day of
December 1959, and so on. In other formats except yearly (%ty), 0 means the first time period
(quarter, day, second, etc.) at the beginning of the year 1960.
To figure out the number that corresponds to a given date, you can use functions like tq(1989q4)
for a quarter, tm(2016apr) for a month, or td(16jan1770) for a day.
P2. Telling Stata You Have Time Series or Panel Data
You must declare your data as time series or panel data in order to use time-related commands:
tsset timevar
Tell Stata you have time series data, with the time listed in variable
timevar.
tsset idvar timevar
Tell Stata you have panel data, with the idvar being a unique ID for each
individual in the sample, and timevar being the measure of time.
P3. Lags, Forward Leads, and Differences
After using the tsset command (see above), it is easy to refer to past and future data. The value of
var one unit of time ago is L.var, the value two units of time ago is L2.var, etc. (the Ls stand for
lag). Future values, although you are unlikely to need them, are F.var, F2.var, etc. Below are
some examples using them. Data must be sorted first, in order by time for time-series data, or in
order by individual and within that by time for panel data.
sort timevar
Sort time-series data.
sort idvar timevar
Sort panel data.
gen changeInX = x - L.x The variable changeInX created here equals x minus its value one year
ago.
29
entity and for the time. There must be unique codes for each entity
in the variable entity, and for each time in the variable time.
By the way, you can instead create dummy variables in the ordinary way and then list them as
variables for your regression. If you need to make dummy variables for a lot of different values, a
little text in the do-file editor will do the job quickly. Here is an example to emulate:
forvalues t = 1900/2010 {
generate year`t' = year==`t'
}
This is a loop like in programming, where t goes from 1900 to 2010. Each time, the line between
the curly brackets gets run. Wherever the `t' appears, Stata plugs in the value of t before running
the line. (In programming lingo, t is a local variable, called in Stata a local macro to avoid
confusion with data variables.) To have values of t plugged in, the t needs to be encased between a
left quote ` and a right quote '.
Q2. Fixed Effects De-Meaning
Statas areg command provides a simple way to include fixed effects in OLS regressions. More
extensive commands are mentioned below, but the following will do for student coursework in
ECON-4570/6560 Econometrics. Statas areg command only lets you de-mean with respect to one
identifier, e.g., person or year but not both if you want fixed effects and time effects, you need to
enter one of them using dummy variables (e.g., by including i.year in your xvarlist).
areg yvar xvarlist, absorb(byvar) vce(robust) Regress the dependent variable yvar on the
independent variables xvarlist and on the dummy variables needed to
distinguish each separate by-group indicated by the byvar variable in
the absorb() option. For example the byvar might be the state, to
include fixed effects for states. Coefficient estimates will not be
reported for these fixed effect dummy variables.
Q3. Other Panel Data Estimators
Students in ECON-6570 Advanced Econometrics will need to use other panel data estimators.
You will need to have declared your panel data first, as in section P2. Then:
xtreg yvar xvarlist, fe
Fixed effects regression. The fe requests fixed effects estimates. This
uses conventional (non-robust) standard errors.
xtreg yvar xvarlist, fe vce(cluster clustervar) Fixed effects regression again, but now with clusterrobust standard errors clustered by the specified variable. Typically
the clustervar is the same as the panelvar used when tsset-ing your
data (see section P2), in order to allow for arbitrary serial correlation
of the error terms within each observation. Actually newer versions
of Stata automatically compute cluster-robust standard errors
(clustered by panelvar), for many panel data commands, if you
merely specify vce(robust) the regression output will indicate this
clustering and in the context of this specific command just
specifying robust standard errors gives you standard errors that are
the same as cluster-robust standard errors.
estimates store fixed
Store estimates after running fixed effects model.
xtreg yvar xvarlist, re vce(robust) Random effects regression. The re requests random effects
estimates. Here the robust option for variance-covariance
estimation requests (Eicker-Huber-White) robust standard errors, but
31
how those predicted probabilities change when the value of a regressor changes. A first command
that helps with this gives you the predicted probabilities for each separate individual in the sample,
given that individuals regressors:
predict probOfOutcome, pr Compute the predicted probability that the dependent variable is 1,
separately for each observation.
However, you might want to compute the probability that Y equals 1 for a hypothetical
individual, for which the values of the regressors are not in the data. How can you do this? One
way is to write out the calculation of the probability using the display command. For example
after the following probit and logit commands, the display command lets you enter a formula for
the whole fitted regression equation (including the cumulative normal or logistic functions) to
calculate the fitted probability, in this case when the variable pi_rat equals 0.3 and the variable
black equals 0. Note the use of _b[varname] to mean the estimated coefficient of the variable
varname in the most recent estimation command.
Here is an example for the probit model:
probit denyMortgage pi_rat black, vce(robust) Estimate a probit model.
scalar z = _b[_cons]+_b[pi_rat]*0.3+_b[black]*0 Calculate x i when the x-variables equal 0.3
and 0 respectively.
display normprob(scalar(z)) Calculate the fitted probit probability that the y-variable equals 1
when the x-variables equal 0.3 and 0 respectively.
Here is an example for the logit model:
logit denyMortgage pi_rat black, vce(robust) Estimate a logit model.
scalar z = _b[_cons]+_b[pi_rat]*0.3+_b[black]*0 Calculate x i when the x-variables equal 0.3
and 0 respectively.
display 1/(1+exp(-scalar(z))) Calculate the fitted logit probability that the y-variable equals 1
when the x-variables equal 0.3 and 0 respectively.
In particular, one usually wants to estimate how much difference it makes if an x-variable is
higher or lower by some amount. The difference made is a function of the values of any other
regressors. For example, if a patient receives an anticancer drug versus does not receive it, the
increase predicted in probability of patient survival depends on any other regressors like health and
age of the patient. Therefore you have to compute two probabilities that y=1, in which you plug in
(a) the value(s) of the variable(s) of interest in alternative cases (such as receiveDrug = 1 versus
receiveDrug = 0), and (b) values of all other variables. For (b), there are two common approaches.
The first approach is to use the mean values of all other regressors in the sample, the idea being
that then your computed probabilities pertain to a hypothetical average individual who is, it is
implicitly assumed, typical. This approach is not desirable because individuals in the sample could
all be far from average and experience very different effects from what you compute. The second
and better approach is to use the actual values of all other regressors and compute a separate
estimated increase in the probability for each separate individual in the sample. Then you can give
the ranges of the predicted increases in probability from lowest to highest among all individuals in
the sample, you can graph how the increases differ depending on values of other variables, and you
can report the average increase in probability across all individuals in the sample. Stata makes it
easy to (1) use the means of other variables, or (2) compute the average increase across all
individuals in the sample:
probit y x1 x2 x3 ..., vce(robust) Estimate a probit model, or you could use a logit instead.
33
margins , at(x1=1)
ordered response models (such as ordered probit and ordered logit), multinomial response models (such
as multinomial probit and multinomial logit), survival analysis models, and many other statistical
models. Listed below are commands for a few of the most commonly used models.
With these models, familiarize yourself with Statas margins command, and use margins after
estimation to interpret the estimation results (section R1 shows how after probit and logit commands).
This is important because otherwise it is all too common that analysts make incorrect interpretations.
S1. Censored and Truncated Regressions with Normally Distributed Errors
If the error terms are normally distributed, then the censored regression model (Tobit model) and
truncated regression model can be estimated as follows.
tobit yvar xvarlist, vce(robust) ll(#) Estimate a censored regression (Tobit) model in which there
is a lower limit to the values of the variables and it is specified by #.
You can instead, or in addition, specify an upper limit using ul(#). If
the censoring limits are different for different observations then use
the cnreg command instead, or more generally if you also have
data that are known only to fall in certain ranges then use the
intreg command instead.
truncreg yvar xvarlist, vce(robust) ll(#) Estimate a truncated regression model in which there is a
lower limit to the values of the variables and it is specified by #.
You can instead, or in addition, specify an upper limit using ul(#).
Be careful that you really do think the error terms are close to normally distributed, as the results
can be sensitive to the assumed distribution of the errors. There are also common models for
truncated or censored data fitting particular distributions, such as zero-truncated count data for
which no data are observed when the count is zero or right-censored survival times; you can find
many such models in Stata.
S2. Count Data Models
The Poisson and negative binomial models are two of the most common count data models.
poisson yvar xvarlist, vce(robust) Estimate a model in which a count dependent variable yvar
results from a Poisson arrival process, in which during a period of
time the Poisson rate of arrivals (that each add 1 to the count in the
y-variable) is proportional to exp(xi') where xi includes the
independent variables in xvarlist.
nbreg yvar xvarlist, vce(robust) Estimate a negative binomial count data model. (This allows the
variance of y to exceed the mean, whereas the Poisson model
assumes the two are equal.)
As always, see the Stata documentation and on-line help for lots more count data models and
options to commands, and look for a book on the subject if you need to work with count data
seriously.
S3. Survival Models (a.k.a. Hazard Models, Duration Models, Failure Time Models)
To fit survival models, or make plots or tables of survival or of the hazard of failure, you must first
tell Stata about your data. There are a lot of options and variants to this, so look for a book on the
subject if you really need to do this. A simple case is:
stset survivalTime, failure(dummyEqualToOneIfFailedElseZero) Tell Stata that you have
survival data, with each individual having one observation. The
variable survivalTime tells the elapsed time at which each individual
35
36
37
C-test is carried out only for the variables vars (if vars involves
multiple variables then separate their names with spaces).
For a heteroskedasticity test after ivregress or ivreg2 (or also after regress), use the third-party
ivhettest command (use ssc install ivreg2, replace or adopath + as in section J2a of this
document). The Pagan-Hall statistic reported is most robust to assumptions; see section 8.9 of
Baums text.
ivhettest
Carry out a heteroskedasticity test.
Get help on ivhettest for options if you want to restrict the set of variables used in the auxiliary
regression ( i in Hayashis section 2.7).
T2. Other Instrumental Variables Models
Some other models have been developed that accommodate instrumental variables methods. For
probit models (0-1 dependent variables), see Statas ivprobit command. For tobit models (with
values above or below a threshold reported as the threshold value), see Statas ivtobit command.
Panel data estimators such as the Arellano-Bond model are available. Also, nonlinear GMM
models in general can be estimated using Statas gmm command.
For panel data instrumental variables methods, see A. Colin Cameron and Pravin K. Trivedis
book Microeconometrics Using Stata (chapter 9), or Christopher Baums book An Introduction to
Modern Econometrics Using Stata.
U. Time Series Models
First tsset your data as in section P above, and note how to use the lag (and lead) operators as described
in section P.
U1. Autocorrelations
corrgram varname
38
After a regression
Add an observation for one more time after the end of the sample. (Use
add(#) to add # observations.) Use browse after this to check what
happened.
predict yhat, xb
Then compute the predicted or forecasted value for each observation.
predict rmsfe, stdf
And compute the standard error of the out-of-sample forecast.
If you want to compute multiple pseudo-out-of-sample forecasts, you could do something like
this:
gen actual = y
gen forecast = .
gen rmsfe = .
forvalues p = 30/50 {
regress y L.y if t<`p'
predict yhatTemp, xb
39
40
42
Remember, the advantage of this sort of system estimation is efficiency, but the disadvantage is risk of
inconsistency. Inconsistency in (potentially) all equations occurs if assumptions are violated for any one
of the equations (also if cross-equation orthogonality is wrong in SUR models). Contrary to a common
misconception, single-equation estimates are consistent, as long as the requisite assumptions are
satisfied. The efficiency advantage may be worth the risk in many cases, but do beware of the risk.
V1. GMM System Estimators
For the generalized method of moments system estimator, Statas gmm command allows very
flexible specification of models, instrumentation, and estimation methods. In fact, the command
allows estimation of nonlinear as well as linear models (see section W). For details, see the Stata
manuals for [R] gmm.
V2. Three-Stage Least Squares
Read the Stata manuals entry for the reg3 command to get a good sense of how it works. Here are
some examples drawn from the Stata manual:
reg3 (consump wagepriv wagegovt) (wagepriv consump govt capital1) Estimate a two-equation
3SLS model in which the two dependent variables, consump and
wagepriv, are assumed to be endogenous. (Dependent variables are
assumed to be endogenous unless you list them in the exog() option.)
The instruments consist of all other variables: wagegovt, govt,
capital1, and the constant term. Note that the consumption equation
estimates will be the same as in 2SLS, since that equation is just
identified.
test [consump]wagegovt [wagepriv]capital1 The test, lincom, and testnl commands work fine
after multi-equation estimations, but you have to specify each
coefficient you are talking about by naming an equation as well as a
variable in an equation. Thus, [consump]wagegovt refers to the
coefficient of the variable wagegovt in the equation named consump.
Stata by default names equations after their dependent variables. For
nonlinear hypothesis tests, refer to coefficients for example using
_b[consump:wagegovt].
reg3 (qDemand: quantity price pcompete income) (qSupply: quantity price praw) , endog(price)
Estimate a two-equation model, naming the equations qDemand and
qSupply since they have the same dependent variable, and treat price
as endogenous. Treat the other three regressors and the constant as
exogenous.
V3. Seemingly Unrelated Regression
Read the Stata manuals entry for the sureg command to get a good sense of how it works. Here is
an example drawn from the Stata manual:
sureg (price foreign mpg displ) (weight foreign length), corr Estimate a two-equation SUR
model. The corr option causes the cross-equation correlation
matrix of the residuals to be displayed, along with a test of the null
hypothesis that the error terms have zero covariance between
equations.
43
Therefore each value of personID would be unique among the observations, but values of
countryID would not be unique. You could match using personID as the identification
code to bring more person-specific information into the dataset, or you could match using
countryID as the identification code to bring more information about each persons
country into the dataset.
If the identification code is unique in each dataset, then there is a one-to-one match,
written 1:1. If the identification code is not unique in the master dataset, but is unique
in the using dataset, then there is a many-to-one match, written m:1. These two cases
pertain to the personID and countryID examples above, if the using datasets have a
unique identification code in each row. If a using dataset does not have unique
identification code, then there would be a one-to-many or many-to-many match, 1:m or
m:m.
A 1:m match could arise if you reverse the order of the master and using datasets in
the countryID match above: you start with a dataset of country information as your
master dataset, and you match to the dataset of person information as your using dataset.
Because the using dataset contains multiple matching rows for each row in the master
dataset, there will be more rows after the merge than there were in the using dataset.
The result will be the same regardless which dataset is the using dataset and which is the
master dataset subject to some caveats discussed below (if variables other than the
identification code have the same name in the two datasets, or if not all observations are
retained, there can be differences).
Mistakes in matching could arise if you meant to perform a 1:1 match but actually
carried out a 1:m or m:1 match then the resulting number of observations might be
something other than what you intended sometimes because of missing values in the
identification code but commonly also because for some reason you have more than one
entry for a code that you meant to be unique. Usually you know what kind of match
should arise, and Stata requires you to specify this information. Indeed, this is really
important to avoid horrible mistakes. For m:m matches Statas merge command does not
do what you would expect it does not create all the relevant pairs; instead you must use
Statas joinby command.
Keeping matching, master-only, and using-only observations. It may be that not all
observations have matches across the master and using files. When no matches exist,
certain observations are orphans for which it is not possible to add columns of data from
the other dataset, so the added variables can only contain missing values. You may not
want these orphans kept in the resulting data, particularly for orphans from the using
dataset. Therefore Stata differentiates between matching (3), master-only (1), and usingonly (2) observations. It creates a variable named _merge that contains the numbers 3, 1,
and 2 respectively for these three cases. You can then drop observations that you do not
want after the match.
Even better, you can specify up-front to keep only observations of specific type(s). To
do so, use the keep() option. Inside the option, specify one or more of match,
master, and using, separated by spaces, to cause matching, master-only, and usingonly observations to be kept in the results. All other observations will be dropped in the
results (though not in any data files on your hard disk).
To ensure against mistakes, you can also use an assert() option to state that
everything should match, or that there should never be orphan observations from one of
46
the datasets. If your assertion that this is true turns out to be violated, then Stata will stop
with an error message so you can check what happened and fix possible problems. Inside
the assert() option, again specify one or more of match, master, and using,
separated by spaces, to assert that the results will contain only matching, master-only, and
using-only observations.
Variables other than the identification code that are in both master and using datasets. If
a variable in the using dataset, other than the identification code, already exists in the
master dataset, then it is not possible to bring that column of data into the results as an
independent column (at least, not with the same variable name, and Stata just doesnt
bring it in). The update option to the merge command causes missing values to be
filled in using values in the using dataset, and the update and replace options together
causes the reverse in which the using datasets values are preferred except where they
have missing values. For matching observations with variables with the same name in
both datasets, if you use the update option, then _merge can take values not just of 1, 2,
or 3, but also of 4 when a missing value was updated from the other dataset, or of 5 when
there were conflicting non-missing values of a variable in the two datasets.
Reading in only selected variables. If you only want to read in some of the variables
from the using dataset, use the keepusing(varlist) option.
Before using the merge command, therefore, you need to go through each of the above issues and
figure out what you want to do. Then you can use commands such as the following:
merge 1:1 personID using filename
Match in observations from the using dataset, with
personID as the identification code variable.
merge 1:1 country year month using filename Match in observations from the using dataset, with
country, year, and month jointly as the identification code.
merge 1:1 personID using filename, keep(match master)
Match in observations from the using
dataset, with personID as the identification code variable, and only
keep observations that match or are in the master dataset; ignore
observations that are in the using dataset only.
merge 1:1 personID using filename, assert(match)
Match in observations from the using
dataset, with personID as the identification code variable, and assert
that all observations in each dataset match if they do not, stop with
an error message.
merge 1:1 _n using filename This one-to-one merge assumes that each observation i in the master
dataset matches to each observation i in the using dataset. This is
dangerous because its easy to mistakenly have a wrong sort order,
so this is not recommended!
merge m:1 countryID using filename Match in observations from the using dataset, with
personID as the identification code variable. This is specified as a
many-to-one match, so the master dataset may contain multiple
observations with the same countryID.
merge 1:m countryID using filename Match in observations from the using dataset, with
personID as the identification code variable. This is specified as a
one-to-many match, so the using dataset may contain multiple
observations with the same countryID.
joinby familyID using filename Carry out a m:m match in which you want all pairs of matching
observations. This is not what you get using merge m:m, and you
47
should not use merge m:m unless you really know what you are
doing. See Statas help for this command for further information
about options.
The merge command will display the number of resulting observations with _merge equal to 1, 2,
and 3. Always check the values of _merge after merging two datasets, to avoid errors.
X3. Reshaping Data
Often, particularly with panel data, it is necessary to convert between wide and long forms of
a dataset. Here is a trivially simple example:
Wide Form:
personid
1
2
income2005
32437
50061
income2006
33822
23974
income2007
41079
28553
Long Form:
personid
1
1
1
2
2
2
year
2005
2006
2007
2005
2006
2007
income
32437
33822
41079
50061
23974
28553
birthyear
1967
1967
1967
1952
1952
1952
birthyear
1967
1952
This is a trivially simple example because usually you would have many variables, not just
income, that transpose between wide and long form, plus you would have many variables, not just
birthyear, that are specific to the personid and dont vary with the year.
Trivial or complex, all such cases can be converted from wide to long form or vice versa using
Statas reshape command:
reshape long income, i(personid) j(year) // Starting from wide form, convert to long form.
reshape wide income, i(personid) j(year) // Starting from long form, convert to wide form.
If you have more variables that, like income, need to transpose between wide and long form, and
regardless of how many variables there are that dont vary with the year, just list the transposing
variables after reshape long or reshape wide, e.g.:
reshape long income married yrseduc, i(personid) j(year) Starting from wide form, convert to
long form.
reshape wide income married yrseduc, i(personid) j(year) Starting from long form, convert to
wide form.
X4. Converting Between Strings and Numbers
Use the describe command to see which variables are strings versus numbers:
describe
If you have string variables that contain numbers, an easy way to convert them to numbers is to
use the destring command. The tostring command works in the reverse direction. For example, if
you have string variables named year, month, and day, and the strings really contain numbers, you
could convert them to numbers as follows:
48
destring year month day, replace Convert string variables named year, month, and day, to
numeric variables, assuming the strings really do contain numbers.
You could convert back again using tostring:
tostring year month day, replace Convert numeric variables named year, month, and day, to
string variables.
When you convert from a string variable to a numeric variable, you are likely to get an error
message because not all of the strings are numbers. For example, if a string is 2,345,678 then
Stata will not recognize it to be a number because of the commas. Similar, values like see note
or >1000 cannot be converted to numbers. If this occurs, Stata will by default refuse to convert
a string value into a number. This is good, because it points out that you need to look more closely
to decide how to treat the data. If you want such non-numeric strings to be converted to missing
values, instead of Stata stopping with an error message, then use the force option to the destring
command:
destring year month day, replace force Convert string variables named year, month, and day, to
numeric variables. If any string values do not seem to be numbers,
convert them to missing values.
Like most Stata commands, these commands have a lot of options. Get help on the Stata
command destring, or consult the Stata manuals, for more information.
X5. Labels
What if you have string variables that contain something other than numbers, like male versus
female, or peoples names? It is sometimes useful to convert these values to categorical
variables, with values 1,2,3,, instead of strings. At the same time, you would like to record
which numbers correspond to which strings. The association between numbers and strings is
achieved using what are called value labels. Statas encode command creates a labeled numeric
variable from a string variable. Statas decode command does the reverse. For example:
encode personName, generate(personNameN)
decode personName, generate(personNameS)
If you do a lot of encoding and decoding, try the add-on commands rencode, rdecode, rencodeall,
and rdecodeall (outside RPI computer labs: from Statas Help menu, choose Search and click the
button for Search net resources, search for rencode, click on the link that results, and click
click here to install; in my econometrics classes at RPI: follow the procedure in section J2a).
This example started with a string variable named personName, generated a new numeric
variable named personNameN with corresponding labels, and then generated a new string variable
personNameS that was once again a string variable just like the original. If you browse the data,
personNameN will seem to be just like the string variable personName because Stata will
automatically show the labels that correspond to each name. However, the numeric version may
take up a lot less memory.
If you want to create your own value labels for a variable, thats easy to do. For example,
suppose a variable named female equals 1 for females or 0 for males. Then you might label it as
follows:
label define femaleLab 0 "male" 1 "female" This defines a label named femaleLab.
label values female femaleLab This tells Stata that the values of the variable named female
should be labeled using the label named femaleLab.
Once you have created a (labeled) numeric variable, it would be incorrect to compare the
contents of a variable to a string:
summarize if country=="Canada" This causes an error if country is numeric!
49
However, Stata lets you look up the value corresponding to the label:
summarize if country=="Canada":countryLabel You can look up the values from a label this
way. In this case, countryLabel is the name of a label, and
"Canada":countryLabel is the number for which the label is
Canada according to the label definition named countryLabel.
If you do not know the name of the label for a variable, use the describe command, and it will tell
you the name of each variables label (if it has a label). You can list all the values of a label with
the command:
label list labelname
This lists all values and their labels for the label named labelname.
Stata also lets you label a whole dataset, so that when you get information about the data, the
label appears. It also lets you label a variable, so that when you would display the name of the the
variable, instead the label appears. For example:
label data "physical characteristics of butterfly species" This labels the data.
label variable income "real income in 1996 Australian dollars" This labels a variable.
X6. Notes
You may find it useful to add notes to your data. You record a note like this:
note: This dataset is proprietary; theft will be prosecuted to the full extent of the law.
However, notes are not by seen by users of the data unless the users make a point to read them.
To see what notes there are, type:
notes
Notes are a way to keep track of information about the dataset or work you still need to do. You
can also add notes about specific variables:
note income: Inflation-adjusted using Australian census data.
X7. More Useful Commands
For more useful commands, go to Statas Help menu, choose Contents, and click on Data
management.
50