0% found this document useful (0 votes)
11 views8 pages

Stata Tutorial: Data Analysis Basics

This Stata tutorial provides an introduction to the software's features, including its interface, commands, and data manipulation capabilities. It covers topics such as loading datasets, performing descriptive statistics, creating graphs, and running regressions. The tutorial emphasizes the importance of command-line usage for reproducibility and offers guidance on efficient project management within Stata.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views8 pages

Stata Tutorial: Data Analysis Basics

This Stata tutorial provides an introduction to the software's features, including its interface, commands, and data manipulation capabilities. It covers topics such as loading datasets, performing descriptive statistics, creating graphs, and running regressions. The tutorial emphasizes the importance of command-line usage for reproducibility and offers guidance on efficient project management within Stata.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Stata Tutorial

Moussa DABO

October 2017

1 Introduction
Stata is a powerful statistical software, very suitable for data manipulation. It integrates most of the
statistical analysis techniques (both classical and recent) and equipped with one of the best production systems
of graphs. Compared to other data processing software, Stata is quite fast and easy.
of use.
This tutorial is an introduction to the main features of Stata. It is based on the Stata Tutorial by Germán.
Rodríguez, available on celien, essentially includes 4 parts. The first is dedicated to a presentation
from the software (interface, operation, . . . ). The other sections successively deal with data analysis, the
production of graphs and programming in Stata.

1.1 Presentation of Stata

Stata is available for Windows, OS X, and Linux environments. The standard version is Stata/IC (Intercooled)
Stata) allows the manipulation of databases containing a maximum of 2,047 variables. There is also an edition
special (professional version), Stata/SE, for which this number rises to 32,766. Finally, the Stata/MP version.
utilize the possibilities of parallel computation on multi-processor machines and gives the opportunity to work with
even larger data sets. In addition, these versions exist in 32-bit and 64-bit.

1.1.1 The Stata interface

Upon first launch, the Stata interface includes 5 windows, arranged as shown in the following figure.

Figure 1: Stata Startup Interface

1
It is at the command window level that you need to enter the instructions (commands) to be executed by the software.
The results (or an error if the syntax is incorrect) are then displayed in the Results window. Next,
la commande est ajoutée à la liste sur la fenêtreReviewsituée à gauche. Il est ensuite possible de revenir sur
any order with a simple click on this list. There is then the Variables window, located in the corner
upper right of the interface, which contains a list of the database variables (if you have loaded any)
Finally, the Properties window, introduced with version 12 of Stata, provides an overview of the metadata.
It is possible to modify this display (change the size, the background color, or even close certain ones.
of these windows), as well as the font styles used for each window at the dialog box level
Preferences accessible from the menu bar.
Other windows (Graph, Viewer, Variables Manager, Data Editor and File Editor) will be presented later.
of this tutorial.
Since version 8 of the software, the graphical interface (GUI) of Stata allows for the selection of commands and
options from the menu and thus work with the software without programming. However, the use
It is not recommended because it does not allow for reproducibility of results. There are also several
features of Stata that are not accessible from the GUI, including contributions from developers
independent. Thus, this tutorial does not mention the GUI in the following.

1.1.2 The commands in Stata

Stata can be used as a calculator with the commanddisplayas in the following examples (the
The point located at the beginning of the line is a way to distinguish lines for Stata and is not part of the command:
. display 2+2
4
. display 2 * ttail(20, 2.1)
.04861759

Commands in Stata are case-sensitive. displayandDisplaydo not mean the same thing and
The second command will produce an error. It is possible to shorten the commands and in the documentation.
as in the online help, the shortest possible abbreviation for each command is underlined and this formality
is also adopted for this tutorial (the shortest possible abbreviation of the commanddisplayis d for example).
The second example shows the use of a built-in function that gives a p-value, 2 times the probability that a
The Student's t statistic with 20 degrees of freedom exceeds the value of 2.1 in this case.
If executing a command produces an error, simply select it in the Review window to modify it.
Syntax if you know the source of the error. Otherwise, it is always possible to get help online.

1.1.3 Get Help

To get help with a command or a built-in function, you need to type help command_name, who
attach the help on a new window called Viewer. You can also typehelp command_namefor
to have help on the Results window, but this is not recommended.
If you do not know the name of the command to execute a particular task, you can use the
ordersearchwho scours the Stata documentation and other resources to find commands that
corresponding to your search. For example, the commandsearch linear regressiongive a comprehensive list
commands, functions, books, and even video tutorials on linear regression documented at the help level
official.
Furthermore, since version 11, all the documentation of Stata is available in PDF files that you can
download. For more details on online help, typehelp helpThere are also several forums and websites.
dedicated where you can ask a question about an order or a task you want to perform and get
a satisfactory response within a reasonable timeframe.

1.1.4 Loading an embedded database

There are some example datasets in the Stata installation folder. To see the list of
all the bases recorded during the installation of Stata, typesystem use directoryThe loading of one of these databases is
Do as in the following example which imports data on life expectancy and GDP of 68 countries in 1998. The
The command describes gives an overview of the content of the imported file.

. sysuse lifeexp, clear


(Life expectancy, 1998)
. desc
Contains data from /Applications/Stata/ado/base/l/[Link]

2
obs: 68 Life expectancy, 1998
vars: 6 26 Mar 2014 09:40
size: 2,652 (dta has notes)

storage display value


variable name type format label variable label

region byte %12.0g region Region


country str28 (s Country
population growth float %9.0g Avg. annual % growth
the exp byte %9.0g Life expectancy at birth
gnppc float %9.0g GNP per capita
safewater byte %9.0g *
* indicated variables have notes

Sorted by:

It appears that the database contains 6 variables. It is also commented, and the comments can be consulted.
with the commandnotesThe ordernotes variable_nameallows you to see the notes on a variable
specific.

1.1.5 Descriptive statistics

In this subsection, attention will be focused on 2 variables: life expectancy (lexp) and the GDP per capita
( gnppcThe ordersummarize, followed by the names of variables, provides the values of some statistics on them.
variables. If the command is not followed by a variable name, it is executed for all the variables in the database.
. summarize lexp gnppc
Variable Obs Mean Std. Dev. Min Max

lexp 68 72.27941 4.715315 54 79


gnppc 63 8674.857 10634.68 370 39980

The average life expectancy is therefore 72.3 years and the GDP per capita ranges from $370 to $39,980, with an average
of $8,675. It also appears that there are only 63 observations on per capita GDP: there are therefore values
missing. The following command provides a list of countries whose GNP per capita is not specified.
. list country gnppc if missing(gnppc)

country gnppc

7. Bosnia and Herzegovina .


40. Turkmenistan .
44. Yugoslavia, FR (Serb./Mont.) .
46. Cuba .
56. Puerto Rico .

There are thus 5 countries with missing data. This example illustrates an important feature of the
programming in Stata: the action of any command can be restricted to a part of the data.
If the condition if missing(gnppc) had been excluded, all 68 countries in the database would appear on the list. It is
Note that Stata denotes a missing value with a dot. Missing data is treated in more detail.
in the second part.

1.1.6 Draw a scatter plot

To see how life expectancy varies with GDP per capita, it is possible to create a scatter plot.
with the commandgraphwhich has several sub-commands and options, some of which are reviewed in the
third part of the tutorial.
. graph twoway scatter life_expectancy gnp_per_capita

. graph export [Link], width(500) replace


(file [Link] written in PNG format)

The graph (on the following page) shows a curvilinear relationship between life expectancy and GDP per capita.
At the level of the following subsection, we will see if it is possible to linearize this relationship by taking the logarithm.
the GDP per capita.

1.1.7 Create new variables

Variable creation is done with the commandgeneratefollowed by a new variable name and an expression
Arithmetic. The choice of variable names is important when you are working on a project. It is necessary to

3
Figure 2: Life expectancy at birth according to GDP per capita

especially to ensure that the variable name gives an idea of what it evaluates. For the logarithm of the
GDP per capita for example, we will chooseloggnppcNames of the typelog_gnp_pcorLogGnpPcare also
commonly used. However, to have internal consistency, the same name format must be used for all
the variables.
The integrated log function calculates the logarithm of the variable provided as an argument:
. gen loggnppc = log(gnppc)
(5 missing values generated)

The missing values generated correspond to countries whose GDP per capita is not provided.

1.1.8 Simple linear regression

We can now perform a regression of life expectancy on the logarithm of per capita GDP.
orderregress, followed by the name of the independent variable and then the regressors (only one in our case) allows
to perform this regression.
. regress lexp loggnppc
Source SS df MS Number of observations = 63
F(1, 61) = 97.09
Model 873.264865 1 873.264865 Prob > F = 0.0000
Residual 548.671643 61 8.99461709 R-squared = 0.6141
Adj R-squared = 0.6078
Total 1421.93651 62 22.9344598 Root MSE = 2.9991

forth Coef. Standard Error t P>|t| [95% Confidence Interval]

loggnppc 2.768349 .2809566 9.85 0.000 2.206542 3.330157


_cons 49.41502 2.348494 21.04 0.000 44.71892 54.11113

This regression is based on the 63 observations with complete data. Stata automatically eliminates all
the observations with a missing value, whether for the independent variable or for the regressors. At
the light of the result of this command, we can say that the logarithm of per capita GNP 'explains' 61%
of the variance of life expectancy. It also appears that a 1% increase in per capita GNP translates into a
increase in life expectancy by 0.0277 years.
After a regression, you can type the command againregwithout the arguments to review the results.

4
1.1.9 Post-estimation commands

Stata has a large number of commands for post-estimation analysis. In particular, there is the
The predict command generates the model's predictions as well as the residuals. For example,
. predict plexp
(optionxbassumed; fitted values)
(5 missing values generated)

create a new variable (}plexpwhich includes the life expectancies predicted by the previous model. It is to
Note that the prediction is made even for countries that have been excluded from the regression due to data.
missing. This is a method for estimating missing values.

1.1.10 Representation of data and linear fitting

A common practice after a regression is to overlay the regression line and the scatter plot.
The resulting graph gives an idea of the quality of the fit. It is possible to do this with the
variableplexpthat we have just created, but by indicating the typelfitto the ordergraphfrom Stata as
In the following example, we obtain the desired result directly.
. graph twoway (scatter lexp loggnppc) (lfit lexp loggnppc)
. graph export [Link], width(500) replace
(file [Link] written in PNG format)

Figure 3:

In this command, each expression in a parenthesis defines a different graph that is superimposed on
others. The fit seems "reasonably good", but we have the presence of outliers.

1.1.11 Make a list of a selection of observations

It is difficult not to notice the country located at the bottom left of the graph, which has a life expectancy
particularly low. With the commandlistit is possible to filter the database to identify this country. By
For example, the following command establishes the list of countries with a life expectancy of less than 55 years.

. list country lexp plexp if lexp < 55, clean


country lexp plexp
50. Haiti 54 66.06985

It appears that the country in question was Haiti, with a life expectancy 12 years lower than predicted.
based on GNP per capita. The wordcleanest option that removes the borders on the table resulting from the
orderlistFor each command, it is possible to specify options and we will go into more detail.
on this point in the following. If you want to see the life expectancy in France, you can type:
5
. list gnppc loggnppc lexp plexp if country == "France", clean
gnppc loggnppc the exp plexp
14. 24210 10.09452 78 77.36018

The double equality allows evaluating a logical expression. The commandx = 2assign the value 2 to the variable x
while the commandex == 2 check if the variable x has the value 2.

1.2 Efficient use of Stata

The commands and results displayed in the Results window disappear when you exit Stata. Therefore,
if you need to save your results or your orders (when you are working within a project
for example), it is important to follow the following instructions.

1.2.1 Create a project folder

Stata loads and saves your data in a folder namedworking directoryIt is possible to specify
a folder of your choice with the commandcd, followed by the path to your folder. The commandpwdstick it
the path of the directory you are working in. It is recommended to create a folder in which
You will have your data and code files for each of your projects and start each session by defining the
work directory.
For specifying the path of a folder, Stata does not differentiate between slashes. \ and/You
you can therefore use either one interchangeably. The commandcreate directoryallows you to create a folder and the command
dirgive the list of all the files present in a directory. You can also copy (with the command
copy) or delete (erase) a file from Stata.

1.2.2 Open a log file

To permanently save your orders and the results of their execution, you need to create (or
open) a log file at the start of your session with the command:
log using file_name, text replace
Stata will then save everything you have in the Results window to the file you specified. The option
textpermet d’enregistrer le fichier sous format texte et de pouvoir l’ouvrir avec des éditeurs autres que leViewer
from Stata. If the optiontextdoes not appear on the order, the file is saved in SMCL format and cannot
can only be opened with the Viewer. However, it is possible to save it in SMCL format and convert it to the format
text or PDF with the commandtranslateThe optionreplaceindicate to Stata to replace the old file
overwrite the same file (if it exists) with this new file. To append new results to an existing file, it
must use the append option. The following command allows you to close a log file.
capture log close
The command capture tells Stata not to display an error if no log file is open.

Always use code files (Do File)

The do file is just a script with Stata commands. You can create it with the Do-File Editor that comes with it.
Stata or any other editor. You just need to make sure that the file is saved with the extension
.doHowever, editing the do-files with the Stata editor offers a number of advantages such as the ability
to execute directly all or part of your code from the editor. If you are using another editor (such as
Notepad or Ms. Word), the command to nom_file will allow you to run your file.

Always comment and annotate your code file

It is important to always properly annotate your code file so that it is understandable to others. Thus,
You must insert comments above your commands to explain what you are trying to do. For
To comment a line of code, simply insert the symbol * at the beginning of the line.
If you are working on an undo file, there are 2 other ways to insert comments. The double slashes (// )
allow you to indicate to Stata that everything to the right of these is to be ignored during execution.
For example, you can write:
gen one = 1 // This variable will serve as a constant in the model

6
Stata will also ignore everything you put in between./* and*/ during execution. These symbols allow you
thus making comments on several lines, or even inserting a comment between segments of a
same line of code.
There is a third type of comment that is used to write a command over multiple lines. Indeed,
lorsque vous avez à écrire une longue commande, il faut penser à la mettre sur plusieurs lignes pour améliorer la
readability of your code. And to indicate to Stata that the command continues on the next line, you can use
the 3 slashes\\\Stata considers everything to the right of the 3 bars as comments and
continue the execution of the command at the next line. For example, you can write:
two-way graph (scatter lexp loggnppc)
(lfit lexp loggnppc)
or equivalently:
twoway graph (scatter lexp loggnppc)
*/ (lfit lexp loggnppc)
An alternative to these 2 writings (only on the do file) is to indicate to Stata the symbol that marks the end.
of an order such as:
#delimit ;
twoway graph (scatter lexp loggnppc)
(lfit lexp loggnppc) ;
to say that each command must end with a semicolon. But if you adopt this convention, you
you must adhere to it for all subsequent commands. To return to the default configuration, type
#delimit cr
Moreover, it is always recommended to start each leaf with comments that include the title,
author's name and the date. It may also be useful to note the metadata.

1.2.6 An Example of Do File

Below is a simple thread to reproduce all the results we have achieved so far. It is not good.
commented because all the orders have been discussed in the above.
Stata Tutorial
Moussa DABO - October 2017

version 14
clear
capture log close
log using Tutorial, text replace

display 2+2
display 2 * ttail(20,2.1)

sysuse lifeexp // Loading the data


desc
summarize the expansion of the GNPP

list country gnppc if missing(gnppc)

graph twoway scatter lexp gnppc, ///


title(Life Expectancy and GNP ) xtitle(GNP per capita)
graph export [Link], width(400) replace // save in PNG format
generate log of gnppc = log(gnppc)
regress lexp loggnppc

predict plexp

two-way graph (scatter lexp loggnppc) (lfit lexp loggnppc)


, title(Life Expectancy and GNP) xtitle(log GNP per capita)
graph export [Link], width(400) replace

list country lexp plexp if lexp < 55, clean


list gnppc loggnppc lexp plexp if country == "United States", clean
log close

7
The first command indicates to Stata that the file has been written with version 14. Thus, all the
Commands will be well interpreted by future versions, even if their syntax evolves.

1.2.7 Syntax of a Stata command

So far we have used Stata commands without commenting on their structure. Below, a command
typical and a brief description of the elements of its syntax. The words in bold are the keywords and those between the
crochets, the optional elements.
[byvarlist:]command[varlist] [=exp] [ifexp] [inrange] [weight] [usingnom_file] [,options]
command:The only essential element for execution is the command itself. It is most often a
action verb (in English). As mentioned above, Stata commands are case sensitive and
may be abbreviated.
The command is most often followed by the name of one or more variables as in describe.
lexpandregress lexp loggnppcVariable names are also case-sensitive and can be abbreviated.
by the smallest number of characters that does not change the fact that they are unique. However, the use
Abbreviations for variable names are not recommended. It is possible to refer to multiple
variables at the same time using wildcard characters such asv*or name ranges such as
v101-v105.
exponentialThe commands used to generate new variables like ingenerate log_gnp = log(gnp) ,
include arithmetic expressions. We will return with more details on expressions at the level of
the section on data manipulation.
if expand in range:As seen earlier, it is possible to execute a command on only a part
data using a logical condition. The relational operators are <, <=, ==, >= and >; the
Negation is expressed using the symbols ! and ~.
weight:Certain commands allow for weighting observations or variables. Typehelp
weights for more details.
using_file_name:The keywordusingintroduce a file name that may be on your hard drive, a server
local or even on the internet. More details in Section 2.
options:Most orders haveoptionswhich are specified after a comma. To see the list of
For options of a given command, type help command_name.
byvarlist:It is possible to repeat the action of certain commands for groups of observations defined by
the values of the variables on the list varlist.

You might also like