Introduction Stata
Introduction Stata
research
Christopher F Baum
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 1 / 120
Overview of the Stata environment
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 2 / 120
Overview of the Stata environment
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 3 / 120
Overview of the Stata environment
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 4 / 120
Overview of the Stata environment
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 5 / 120
Overview of the Stata environment
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 6 / 120
Overview of the Stata environment Portability
C:\Stata\StataData\[Link]
or
/users/baum/statadata/[Link]
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 7 / 120
Overview of the Stata environment Stata’s user interface
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 8 / 120
Overview of the Stata environment Stata’s user interface
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 9 / 120
Overview of the Stata environment Stata’s user interface
The Toolbar contains icons that allow you to Open and Save files, Print
results, control Logs, and manipulate windows. Some very important
tools allow you to open the Do-File Editor, the Data Editor and the Data
Browser.
The Data Editor and Data Browser present you with a spreadsheet-like
view of the data, no matter how large your dataset may be. The
Do-File editor, as we will discuss, allows you to construct a file of Stata
commands, or “do-file”, and execute it in whole or in part from the
editor.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 10 / 120
Overview of the Stata environment Stata’s user interface
You generally will not want to locate or save files in the default cwd. A
common strategy is to set up a directory for each project or task in a
convenient location in the filesystem and change the cwd to that
directory when working on that task. This can be automated in a
do-file with the cd command.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 11 / 120
Overview of the Stata environment Stata’s user interface
There are four windows in the default interface: the Review, Results,
Command and Variables window. You may alter the appearance of any
window in the GUI using the Preferences− >General dialog, and make
those changes on a temporary or permanent basis.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 12 / 120
Overview of the Stata environment Stata’s user interface
Once you have loaded data into the program, the Variables window will
be populated with information on each variable. That information
includes the variable name, its label (if any), its type and its format.
This is a subset of information available from the describe command.
Let’s look at the interface after I have loaded one of the datasets
provided with Stata, uslifeexp, with the sysuse command and
given the describe and summarize commands:
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 13 / 120
Overview of the Stata environment Stata’s user interface
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 14 / 120
Overview of the Stata environment Stata’s user interface
Notice that the three commands are listed in the Review window. If any
had failed, the _rc column would contain a nonzero number, in red,
indicating the error code. The Variables window contains the list of
variables and their labels. The Results window shows the effects of
summarize: for each variable, the number of observations, their
mean, standard deviation, minimum and maximum. If there were any
string variables in the dataset, they would be listed as having zero
observations.
Try it out: type the commands
sysuse uslifeexp
describe
summarize
We may also write a do-file in the do-file editor and execute it. The
Do-File Editor icon on the Toolbar brings up a window in which we may
type those same three commands, as well as a few more:
sysuse uslifeexp
describe
summarize
notes
summarize le if year < 1950
summarize le if year >= 1950
After typing those commands into the window, the rightmost icon, with
tooltip Do, may be used to execute them.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 16 / 120
Overview of the Stata environment Using the Do-File Editor
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 17 / 120
Overview of the Stata environment Using the Do-File Editor
In this do-file, I have included the notes command to display the notes
saved with the dataset, and included two comment lines. There are
several styles of comments available. In this style, anything on a line
following a double slash (//) is ignored.
You may use the other icons in the Do-File Editor window to save your
do-file (to the cwd or elsewhere), print it, or edit its contents. You may
also select a portion of the file with the mouse and execute only those
commands. Note that the tooltip changes to Do Selected Lines.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 18 / 120
Overview of the Stata environment Using the Do-File Editor
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 19 / 120
Overview of the Stata environment Using the Do-File Editor
Try it out: use the Do-File Editor to open the do-file [Link], and run
the file.
Try selecting only those last four lines and run those commands.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 20 / 120
Overview of the Stata environment The help system
The rightmost menu on the menu bar is labeled Help. From that menu,
you can search for help on any command or feature. The Help
Browser, which opens in a Viewer window, provides hyperlinks, in blue,
to additional help pages. At the foot of each help screen, there are
hyperlinks to the full manuals, which are accessible in PDF format.
The links will take you directly to the appropriate page of the manual.
You may also search for help at the command line with help
command. But what if you don’t know the exact command name?
Then you may use search or its expanded version, findit, each of
which may be followed by one or several words.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 21 / 120
Overview of the Stata environment The help system
Try it out: when you are connected to the Internet, type the command
search baum, au
and then try
findit baum
Note the hyperlinks that appear on URLs for the books and journal
articles, and on the individual software packages (e.g., st0030_3,
archlm).
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 22 / 120
Overview of the Stata environment Stata’s update facility
Updates during the life of the version you own are free. You need only
have a licensed copy of Stata and access to the Internet (which may
be by proxy server) to check for and, if desired, download the updates.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 23 / 120
Overview of the Stata environment Extensibility
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 24 / 120
Overview of the Stata environment Extensibility
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 25 / 120
Overview of the Stata environment Extensibility
The importance of this program design goes far beyond the limits of
official Stata. Since the adopath includes both Stata directories and
other directories on your hard disk (or on a server’s filesystem), you
may acquire new Stata commands from a number of web sites. The
Stata Journal (SJ), a quarterly refereed journal, is the primary method
for distributing user contributions. Between 1991 and 2001, the Stata
Technical Bulletin played this role, and a complete set of issues of the
STB are available on line at the Stata website.
The SJ is a subscription publication (articles more than three years old
freely downloadable), but the ado- and sthlp-files may be freely
downloaded from Stata’s web site. The Stata help command
accesses help on all installed commands; the Stata command findit
will locate commands that have been documented in the STB and the
SJ, and with one click you may install them in your version of Stata.
Help for these commands will then be available in your own copy.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 26 / 120
Overview of the Stata environment Extensibility
But this is only the beginning. Stata users worldwide participate in the
StataList listserv, and when a user has written and documented a new
general-purpose command to extend Stata functionality, they
announce it on the StataList listserv (to which you may freely
subscribe: see Stata’s web site).
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 27 / 120
Overview of the Stata environment Extensibility
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 28 / 120
Overview of the Stata environment Extensibility
The command ssc new lists, in the Stata Viewer, all SSC packages
that have been added or modified in the last month. You may click on
their names for full details. The command ssc hot reports on the
most popular packages on the SSC Archive.
The Stata command adoupdate checks to see whether all packages
you have downloaded and installed from the SSC archive, the Stata
Journal, or other user-maintained net from... sites are up to date.
adoupdate alone will provide a list of packages that have been
updated. You may then use adoupdate, update to refresh your
copies of those packages, or specify which packages are to be
updated.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 29 / 120
Overview of the Stata environment Extensibility
Stata will now respond to the command hello. It’s that easy. Try it out!
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 30 / 120
Working with the command line Stata command syntax
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 31 / 120
Working with the command line Command template
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 32 / 120
Working with the command line Programmability of tasks
Programmability of tasks
Stata makes reproducibility very easy through a log facility, the ability
to generate a command log (containing only the commands you have
entered), and the do-file editor which allows you to easily enter,
execute and save sequences of commands, or program fragments.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 33 / 120
Working with the command line Programmability of tasks
Going one step further, if you use the do-file editor to create a
sequence of commands, you may save that do-file and reuse it
tomorrow, or use it as the starting point for a similar set of data
management or statistical operations. Working in this way promotes
reproducibility, which makes it very easy to perform an alternate
analysis of a particular model. Even if many steps have been taken
since the basic model was specified, it is easy to go back and produce
a variation on the analysis if all the work is represented by a series of
programs.
One of the implications of the concern for reproducible work: avoid
altering data in a non-auditable environment such as a spreadsheet.
Rather, you should transfer external data into the Stata environment as
early as possible in the process of analysis, and only make permanent
changes to the data with do-files that can give you an audit trail of
every change made to the data.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 34 / 120
Working with the command line Programmability of tasks
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 35 / 120
Working with the command line Local macros and scalars
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 36 / 120
Working with the command line Local macros and scalars
The local macro is an invaluable tool for do-file authors. A local macro
is created with the local statement, which serves to name the macro
and provide its content. When you next refer to the macro, you extract
its value by dereferencing it, using the backtick (‘) and apostrophe (’)
on its left and right:
local george 2
local paul = ‘george’ + 2
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 37 / 120
Working with the command line forvalues and foreach
In other cases, you want to redefine the macro, not evaluate it, and you
should not use an equals sign. You merely want to take the contents of
the macro (a character string) and alter that string. The two key
programming constructs for repetition, forvalues and foreach,
make use of local macros as their “counter”. For instance:
forvalues i=1/10 {
summarize PRweek‘i’
}
Note that the value of the local macro i is used within the body of the
loop when that counter is to be referenced. Any Stata numlist may
appear in the forvalues statement. Note also the curly braces,
which must appear at the end of their lines.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 38 / 120
Working with the command line forvalues and foreach
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 39 / 120
Working with the command line forvalues and foreach
Or, run a regression on variables for each region, and graph the data
and fitted line:
levelsof region, local(regid)
foreach c of local regid {
local rr : label region ‘c’
regress lexp gnppc if region ==‘c’
twoway (scatter lexp gnppc if region ==‘c’) ///
(lfit lexp gnppc if region ==‘c’, ///
ti(Region: ‘rr’) name(fig‘c’, replace))
}
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 40 / 120
Working with the command line forvalues and foreach
local alleps
foreach c of local regid {
regress lexp gnppc if region ==‘c’
predict double eps‘c’ if e(sample), residual
local alleps "‘alleps’ eps‘c’"
}
Within the loop we redefine the macro alleps (as a double-quoted
string) to contain itself and the name of the residuals from that region’s
regression. We could then use the macro alleps to generate a graph
of all three regions’ residuals:
gen cty = _n
scatter `alleps´ cty, yline(0) scheme(s2mono) legend(rows(1)) ///
ti("Residuals from model of life expectancy vs per capita GDP") ///
t2("Fit separately for each region")
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 41 / 120
Working with the command line forvalues and foreach
0 20 40 60 80
cty
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 42 / 120
Working with the command line forvalues and foreach
Global macros
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 43 / 120
Working with the command line Prefix commands
Prefix commands
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 44 / 120
Data management: principles of organization and transformation Missing values
Missing values
Missing value codes in Stata appear as the dot (.) in printed output
(and a string missing value code as well: “”, the null string). It takes on
the largest possible positive value, so in the presence of missing data
you do not want to say
generate hiprice = (price > 10000) but rather
generate hiprice = (price > 10000) if price <.
which then generates an indicator (dummy) variable equal to 1 for
high-priced cars. The indicator will be zero for low-priced cars and
missing for cars with missing prices.
Stata allows for multiple missing value codes (.a, .b, .c, ...,
.z). The standard missing value code (.) is the smallest among
them, so testing for < . will always work. You may also use the missing
function: mi(varname) will return 1 if the observation is a missing
value, 0 otherwise.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 45 / 120
Data management: principles of organization and transformation Missing data handling
An issue that often arises when importing data from external sources
is the proper handling of missing data codes. Spreadsheet files often
use NA to denote missing values, while in some datasets codes such
as -9, -999, or -0.001 are used. The latter instances are
particularly worrisome as they may not be detected unless the
variables’ values are carefully scrutinized.
Note also that there is a missing value for string variables—the null, or
zero-length string—which looks identical to a string of one or more
space characters.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 46 / 120
Data management: principles of organization and transformation Missing data handling
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 47 / 120
Data management: principles of organization and transformation Missing data handling
No matter what methods you have used to input external data to the
Stata workspace, you should immediately save the file in Stata format
and perform the describe and summarize commands. It is much
more efficient to read a Stata-format .dta file with use than to
repeatedly input a text file with any of the commands discussed above.
If the file is large, you may want to use the compress command to
optimise Stata’s memory usage before saving it. compress is
non-destructive; it never reduces the stored precision of a variable.
Before any further use is made of this datafile, examine the results of
the describe and summarize commands and ensure that each
variable has been input properly, and that numeric variables have
sensible values for their minima and maxima.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 48 / 120
Data management: principles of organization and transformation Display formats
Display formats
Each variable may have its own default display format. This does not
alter the contents of the variable, but only affects how it is displayed.
For instance, %9.2f would display a two-decimal-place real number.
The command
format varname %9.2f
will save that format as the default format of the variable, and
format date %tm
will format a Stata date variable into a monthly format (e.g., 1998m10).
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 49 / 120
Data management: principles of organization and transformation Variable labels
Variable labels
Each variable may have its own variable label. The variable label is a
character string (maximum 80 characters) which describes the
variable, associated with the variable via
label variable varname "text"
Variable labels, where defined, will be used to identify the variable in
printed output, space permitting.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 50 / 120
Data management: principles of organization and transformation Value labels
Value labels
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 51 / 120
Data management: principles of organization and transformation The by prefix
The by prefix
You can often save time and effort by using the by prefix. When a
command is prefixed with a bylist, it is performed repeatedly for each
element of the variable or variables in that list, each of which must be
categorical. You may try it out:
sysuse census
by region: summ pop medage
will provide descriptive statistics for each of four US Census regions. If
the data are not already sorted by the bylist variables, the prefix
bysort should be used. The option ,total will add the overall
summary.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 52 / 120
Data management: principles of organization and transformation The by prefix
This is a very handy tool, which often replaces explicit loops that must
be used in other programs to achieve the same end.
The by-group logic will work properly even when some of the defined
groups have no observations. However, its limitation is that it can only
execute a single command for each category. If you want to estimate a
regression for each group and save the residuals or predicted values,
you must use an explicit loop.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 53 / 120
Data management: principles of organization and transformation The by prefix
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 54 / 120
Data management: principles of organization and transformation The by prefix
For instance, if you have individual data with a family identifier, these
commands might be useful:
Here the famsize variable is set to _N, the total number of records for
that family, while the birthorder variable is generated by sorting the
family members’ ages within each family.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 55 / 120
Data management: principles of organization and transformation Generating new variables
A full set of functions are available for use in the generate command,
including the standard mathematical functions, recode functions, string
functions, date and time functions, and specialized functions (help
functions for details). Note that generate’s sum() function is a
running or cumulative sum.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 56 / 120
Data management: principles of organization and transformation Generating new variables
The if exp qualifier is usually more useful, but the in range qualifier
may be used to list a few observations of the data to examine their
validity. To list observations at the end of the current data set,
use if -5/` to see the last five.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 57 / 120
Data management: principles of organization and transformation Generating new variables
You can take advantage of the fact that the exp specified in generate
may be a logical condition rather than a numeric or string value. This
allows producing both the 0s and 1s of an indicator (dummy, or
Boolean) variable in one command. For instance:
The condition & !mi(pop) makes use of two logical operators: &,
AND, and !, NOT to add the qualifier that the result variable should be
missing if pop is missing, using the mi() function. Although numeric
functions of missing values are usually missing, creation of an
indicator variable requires this additional step for safety.
The third logical operator is the Boolean OR, written as |. Note also
that a test for equality is specified with the == operator (as in C). The
single = is used only for assignment.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 58 / 120
Data management: principles of organization and transformation Generating new variables
if (race == "Black") {
raceid = 2
}
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 59 / 120
Data management: principles of organization and transformation Functions for generate, replace
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 60 / 120
Data management: principles of organization and transformation Functions for generate, replace
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 61 / 120
Data management: principles of organization and transformation Functions for generate, replace
Notice that in this example the endqtr variable need not be defined
as string in the generate statement.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 62 / 120
Data management: principles of organization and transformation Functions for generate, replace
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 63 / 120
Data management: principles of organization and transformation Functions for generate, replace
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 64 / 120
Data management: principles of organization and transformation Functions for generate, replace
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 65 / 120
Data management: principles of organization and transformation String-to-numeric conversion and vice versa
String-to-numeric conversion
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 66 / 120
Data management: principles of organization and transformation String-to-numeric conversion and vice versa
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 67 / 120
Data management: principles of organization and transformation String-to-numeric conversion and vice versa
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 68 / 120
Data management: principles of organization and transformation String-to-numeric conversion and vice versa
As the data are tab-delimited, I can read a file with embedded spaces
in the state variable.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 69 / 120
Data management: principles of organization and transformation String-to-numeric conversion and vice versa
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 70 / 120
Data management: principles of organization and transformation String-to-numeric conversion and vice versa
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 71 / 120
Data management: principles of organization and transformation The egen command
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 72 / 120
Data management: principles of organization and transformation The egen command
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 73 / 120
Data management: principles of organization and transformation The egen command
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 74 / 120
Data management: principles of organization and transformation The egen command
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 75 / 120
Data management: principles of organization and transformation The egen command
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 76 / 120
Data management: principles of organization and transformation The egen command
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 77 / 120
Data management: principles of organization and transformation The egen command
Many other egen functions are available; see help egen for details.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 78 / 120
Data management: principles of organization and transformation Time series calendar
Stata supports date (and time) variables and the creation of a time
series calendar variable. Dates are expressed, as they are in Excel, as
the number of days from a base date. In Stata’s case, that date is
1 Jan 1960 (like Unix/Linux). You may set up data on an annual,
half-yearly, quarterly, monthly, weekly or daily calendar, as well as a
calendar that merely uses the observation number.
You may also set the delta of the calendar variable to be other than
1: for instance, if you have data at five-year intervals, you may define
the data as annual with delta=5. This ensures that the lagged value
of the 2005 observation is that of 2000.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 79 / 120
Data management: principles of organization and transformation Time series calendar
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 80 / 120
Data management: principles of organization and transformation Time series calendar
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 81 / 120
Data management: principles of organization and transformation Time series operators
The D., L., and F. operators may be used under a time series
calendar (including in the context of panel data) to specify first
differences, lags, and leads, respectively. These operators understand
missing data, and numlists: e.g. L(1/4).x is the first through fourth
lags of x, while L2D.x is the second lag of the first difference of the x
variable.
It is important to use the time series operators to refer to lagged or led
values, rather than referring to the observation number (e.g., _n-1).
The time series operators respect the time series calendar, and will not
mistakenly compute a lag or difference from a prior period if it is
missing. This is particularly important when working with panel data to
ensure that references to one individual do not reach back into the
prior individual’s data.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 82 / 120
Data management: principles of organization and transformation Time series operators
Using time series operators, you may not only consistently generate
differences, lags, and leads, but may refer to them ‘on the fly’ in
statistical and estimation commands. That is, to estimate an AR(4)
model, you need not create the lagged variables:
regress y L(1/4).y
regress y (-4/4).x
which would regress yt on four leads, four lags and the current value of
xt .
For a “Dickey–Fuller” style regression,
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 83 / 120
Data management: principles of organization and transformation Factor variables
Factor variables
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 84 / 120
Data management: principles of organization and transformation Factor variables
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 85 / 120
Data management: principles of organization and transformation Factor variables
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 86 / 120
Data management: principles of organization and transformation File handling
File handling
These extensions need not be given (except for .ado). If you use
other extensions, they must be explicitly specified.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 87 / 120
Reading external data insheet
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 88 / 120
Reading external data insheet
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 89 / 120
Reading external data infile
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 90 / 120
Reading external data infile
If some of the data are string variables without embedded spaces, they
must be specified in the command:
infile str3 country price mpg displacement using auto2
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 91 / 120
Reading external data infile
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 92 / 120
Reading external data infix
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 93 / 120
Reading external data infix
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 94 / 120
Reading external data Stat/Transfer
If your data are already in the internal format of SAS, SPSS, Excel,
GAUSS, MATLAB, or a number of other packages, the best way to get
it into Stata is by using the third-party product Stat/Transfer.
Stat/Transfer will preserve variable labels, value labels, and other
aspects of the data, and can be used to convert a Stata binary file into
other packages’ formats. It can also produce subsets of the data
(selecting variables, cases or both) so as to generate an extract file
that is more manageable. This is particularly important when the
2,047-variable limit on standard Stata data sets is encountered.
Stat/Transfer is well documented, with on-line help available in both
Windows, Mac OS X and Unix versions, and an extensive manual. It is
remarketed by StataCorp.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 95 / 120
Writing external data outfile, outsheet and file
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 96 / 120
Writing external data postfile and post
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 97 / 120
Combining data sets append
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 98 / 120
Combining data sets append
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 99 / 120
Combining data sets append
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 100 / 120
Combining data sets append
id var 1 var 2
126 .. ..
. .
.. ..
309
dataset2 : . .
.. ..
421 . .
.. ..
604 . .
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 101 / 120
Combining data sets append
These two datasets contain the same variables, as they must for
append to sensibly combine them. If dataset2 contained idcode,
Var1, Var2 the two datasets could not sensibly be appended without
renaming the variables (recall that in Stata, var1 and Var1 are two
separate variables). Appending these two datasets with common
variable names creates a single dataset containing all of the
observations:
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 102 / 120
Combining data sets append
id var 1 var 2
.. ..
112 . .
.. ..
216 . .
.. ..
449 . .
combined : .. ..
126 . .
.. ..
309 . .
.. ..
421 . .
.. ..
604 . .
The rule for append, then, is that if datasets are to be combined, they
should share the same variable names and datatypes (string vs.
numeric). In the above example, if var1 in dataset1 was a float
while that variable in dataset2 was a string variable, they
could not be appended.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 103 / 120
Combining data sets append
Some care must be taken when appending datasets in which the same
variable may exist with different data types (string in one, numeric in
another). For details, see “Stata tip 73: append with care!”, Baum CF,
Stata Journal, 2008, 9:1, 166-168, included in your materials.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 104 / 120
Combining data sets merge
We now describe the merge command, which is Stata’s basic tool for
working with more than one dataset. Its syntax has changed
considerably in Stata version 11.
The merge command takes a first argument indicating whether you are
performing a one-to-one, many-to-one, one-to-many or many-to-many
merge using specified key variables. It can also perform a one-to-one
merge by observation.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 105 / 120
Combining data sets merge
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 106 / 120
Combining data sets merge
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 107 / 120
Combining data sets merge
id
var 22 var 44 var 46
112 .. .. ..
. . .
dataset3 :
.. .. ..
216 . . .
.. .. ..
449 . . .
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 108 / 120
Combining data sets merge
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 109 / 120
Combining data sets merge
The rule for merge, then, is that if datasets are to be combined on one
or more merge keys, they each must have one or more variables with a
common name and datatype (string vs. numeric). In the example
above, each dataset must have a variable named id. That variable can
be numeric or string, but that characteristic of the merge key variables
must match across the datasets to be merged. Of course, we need not
have exactly the same observations in each dataset: if dataset3
contained observations with additional id values, those observations
would be merged with missing values for var1 and var2.
This is the simplest kind of merge: the one-to-one merge. Stata
supports several other types of merges. But the key concept should be
clear: the merge command combines datasets “horizontally”, adding
variables’ values to existing observations.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 110 / 120
Combining data sets Match merge
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 111 / 120
Combining data sets Match merge
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 112 / 120
Reconfiguring data sets
Data are often provided in a different orientation than that required for
statistical analysis. The most common example of this occurs with
panel, or longitudinal, data, in which each observation conceptually
has both cross-section (i) and time-series (t) subscripts. Often one will
want to work with a “pure” cross-section or “pure” time-series. If the
microdata themselves are the objects of analysis, this can be handled
with sorting and a loop structure. If you have data for N firms for T
periods per firm, and want to fit the same model to each firm, one
could use the statsby command, or if more complex processing of
each model’s results was required, a foreach block could be used. If
analysis of a cross-section was desired, a bysort would do the job.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 113 / 120
Reconfiguring data sets collapse
But what if you want to use average values for each time period,
averaged over firms? The resulting dataset of T observations can be
easily created by the collapse command, which permits you to
generate a new data set comprised of summary statistics of specified
variables. More than one summary statistic can be generated per input
variable, so that both the number of firms per period and the average
return on assets could be generated. collapse can produce counts,
means, medians, percentiles, extrema, and standard deviations.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 114 / 120
Reconfiguring data sets reshape
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 115 / 120
Reconfiguring data sets reshape
When data have more than one identifier per record, they may be
organized in different ways. For instance, it is common to find on-line
displays or downloadable spreadsheets of data for individual units—for
instance, U.S. states—with the unit’s name labeling the row and the
year labeling the column. If these data were brought into Stata in this
form, they would be in the wide form, wide form with the same
measurement (population) for different years denoted as separate
Stata variables:
. list, noobs
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 116 / 120
Reconfiguring data sets reshape
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 117 / 120
Reconfiguring data sets reshape
CT 1990 3291967
CT 1995 3324144
CT 2000 3411750
MA 1990 6022639
MA 1995 6141445
MA 2000 6362076
RI 1990 1005995
RI 1995 1017002
RI 2000 1050664
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 118 / 120
Reconfiguring data sets reshape
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 119 / 120
Reconfiguring data sets reshape
With the proper use of reshape, writing data out and reading them
back in is not necessary in Stata. But reshape requires, first of all,
that the data to be reshaped are labelled in such a way that they can
be handled by the mechanical rules that the command applies. In
situations beyond the simple application of reshape, it may require
some experimentation to construct the appropriate command syntax.
This is all the more reason for enshrining that code in a do-file as some
day you are likely to come upon a similar application for reshape.
Christopher F Baum (BC / DIW) Using Stata IMF Institute, Spring 2011 120 / 120