The Stata interface, reading commands, help, the working folder and do files, followed by opening a dataset, variable types, labels and importing Excel and CSV files.
120 minutesLab based exerciseStata 15 or laterBy the end of this session, participants will be able to:
Stata is a statistical package for data management, analysis, graphics and reporting. It is used widely in public health, economics and the social sciences.
summarize exists, but Summarize does not.This course uses the women's individual recode file of the 2022 Bangladesh Demographic and Health Survey (BDHS). It holds the interview records of women of reproductive age, aged 15 to 49, with one row for each woman.
BDIR81FL.DTA, in Stata format.v012 for age. This is more than the default limit of 5,000 variables, so the limit must be raised before the file is opened.Access. Download the dataset from the shared course folder, using the dataset button on the course home page, and save it in your working folder. Use the data for this course only, and cite the source as The DHS Program, BDHS 2022.
| Variable | Meaning |
|---|---|
v001, v002, v003 | Cluster number, household number and respondent line number. Together they identify a woman. |
v005 | Women's sample weight, used in later sessions. |
v012 | Current age of the respondent, in years. |
v024 | Region, that is, the division of residence. |
v025 | Type of place of residence: urban or rural. |
v106 | Highest level of education attained. |
v190 | Wealth index, in five groups. |
v201 | Total number of children ever born. |
Survey weights are introduced after the basic tools are in place, so early summaries are unweighted.
| Window | Purpose |
|---|---|
| Command | Where a single command is typed and executed with Enter. |
| Results | Displays output, including error messages. |
| History | Lists commands run in the session. Older versions call it Review. A double click runs a command again. |
| Variables | Lists the variables of the dataset in memory. Clicking a name pastes it into the Command window. |
| Properties | Shows the label, type and format of the selected variable. |
browse): displays the data without allowing changes.edit): displays the data and allows changes.Browse before you edit. A stray keystroke in the Data Editor can alter a value. Use the Data Browser unless editing is intended.
Small tables can be typed directly into the Data Editor, without writing any command.
var1, var2 and so on. Select a variable and change its name and label in the Properties window.Typing suits very small tables. Larger data should be imported from a file, which is covered later in this session.
Most Stata commands follow one pattern. Everything after the command name is optional.
summarize v012 v201 if v025 == 2, detailThis asks Stata to summarise the variables v012 (age) and v201 (children ever born), only for observations where v025 equals 2, with detailed statistics.
codebook v025 before relying on them.sum for summarize. This course writes commands in full for clarity.bysort v025: summarize v012.| Message | Code | Usual cause |
|---|---|---|
| unrecognized command | r(199) | Misspelt command, or wrong case such as Summarize. |
| variable not found | r(111) | Misspelt variable name, or no dataset loaded. |
| file not found | r(601) | Wrong file name, or the wrong working folder. |
| no; dataset in memory has changed since last saved | r(4) | Loading another dataset without the clear option. |
| no room to add more variables | r(900) | The dataset has more variables than the limit set by maxvar. Raise the limit with set maxvar. |
* Open the help page of a command
help summarize
* Search by topic when the command name is unknown
search regression
* Look for user written commands
findit outreg2Help pages open in the Viewer. Each begins with the syntax, and worked examples appear at the end. Reading the examples first is often the quickest way to learn a command.
Stata reads and writes files in its working folder unless told otherwise. Setting it at the start of each session prevents most file not found errors.
* Show the current working folder
pwd
* Create a folder for the course (run once)
mkdir StataCourse
* Change into it; use quotation marks if the path has spaces
cd "C:\StataCourse"
* The same on a Mac
cd "/Users/yourname/StataCourse"
* List the files in the folder
lsReplace the example paths with a folder on your computer, place the BDHS file in it, and confirm with pwd and ls.
A do file is a plain text file of commands that Stata runs in order. Typing in the Command window suits exploration, whereas a do file is the right place for work that must be repeated, checked or shared.
doedit..do.| Style | Use |
|---|---|
* text | A comment on its own line, with the asterisk at the start. |
// text | A comment at the end of a command line, with a space before the slashes. |
/* text */ | A comment that may run over several lines. |
/// | Continues a long command onto the next line. |
Comments explain why a step is taken. They are ignored when the do file runs.
Stata limits the number of variables that a dataset may hold. In Stata/SE and Stata/MP the default limit is 5,000. The BDHS file has 5,425 variables, so Stata refuses to open it until the limit is raised.
clear all
set maxvar 10000clear all empties the memory. The limit can be changed only while no data are loaded.set maxvar 10000 raises the limit to 10,000 variables for the current session. Add , permanently to keep the setting for later sessions.query memory shows the limit that is currently in force.Stata/BE users. Load only the variables you need, by naming them before the file. This works in every edition.
use v001 v002 v003 v005 v012 v024 v025 v106 v190 v201 using "BDIR81FL.DTA", clearclear all
set maxvar 10000
use "BDIR81FL.DTA", clear
describe, shortuse loads a Stata dataset into memory. The clear option discards any dataset already there.describe, short reports only the number of observations and variables, along with the size of the data.Avoid a plain describe on this file. With 5,425 variables, describe fills the Results window with a very long list. Use the short option first.
lookfor education
lookfor wealth
codebook v106lookfor searches variable names and labels for a word, which is the standard way to find a variable in a DHS file.codebook shows the label, the type, and the coded values of a variable, with their meanings.count
count if v025 == 2count reports the number of observations, optionally those meeting a condition.summarize v012 v201
tabulate v025
tabulate v106
tabulate v025 v106, rowsummarize reports the number of observations, mean, standard deviation, minimum and maximum of numeric variables.tabulate gives frequencies of a categorical variable. With two variables it gives a cross table, and row adds row percentages.Read the output together with the codebook, so that each code is matched to its meaning.
| Kind | Holds | Examples in the BDHS file |
|---|---|---|
| Numeric | Numbers, including coded categories | v012 age, v201 children ever born, v025 residence (coded 1 and 2) |
| String | Text of any kind | Names, free text answers, identifiers such as caseid |
Arithmetic and most statistical commands need numeric variables. A categorical variable is normally stored as a numeric code, with a value label that supplies the words.
A variable label describes the variable. A value label attaches words to numeric codes, so that the code 2 can display as rural.
describe v025
label list V025
tabulate v025
tabulate v025, nolabeldescribe output. In this file the labels are named in capitals, such as V025.label list prints the codes and their words.nolabel option shows the underlying numeric codes instead of the words.save "mydata.dta", replace
use "mydata.dta", clearsave writes the dataset in memory to a .dta file. Without replace, Stata refuses to overwrite an existing file of the same name.saveold "mydata.dta", replace, which writes a copy that older versions can read.Two small files are provided with this session. Both hold the same 300 women, drawn at random from the BDHS file, with readable column names.
| File | Contents |
|---|---|
bdhs_sample.xlsx | Excel workbook with a sheet called Women holding the data and a sheet called Notes describing the columns. |
bdhs_sample.csv | The same data as plain text, with commas between values. |
Download both files from the course folder and save them in the working folder.
import excel "bdhs_sample.xlsx", sheet("Women") firstrow clear
describe
list in 1/5sheet() names the worksheet to read. Without it, Stata reads the first sheet.firstrow tells Stata that the first row holds the variable names.clear discards any dataset already in memory.cellrange(A1:H301).import delimited "bdhs_sample.csv", clear
describe
list in 1/5import delimited reads text files whose values are separated by commas, tabs or another character.delimiter(";") if the separator is not a comma.* Session 1: opening and inspecting data
* Author and date: write here
clear all
set more off
set maxvar 10000
cd "C:\StataCourse"
use "BDIR81FL.DTA", clear
describe, short
summarize v012 v201
tabulate v025
tabulate v106The structure matters most: clear the workspace, set the folder, open the data, then do the work.
| Topic | Remember |
|---|---|
| Windows | Command to type, Results to read, History to repeat, Variables and Properties to inspect the data. |
| Syntax | command, then varlist, then if or in, then a comma and options. |
| Case | Commands and variable names are case sensitive and usually lower case. |
| Errors | A message and a return code appear in red, and the data are not changed. |
| Help | help for a known command, search for a topic. |
| Working folder | pwd shows it, cd changes it, and files are read from it and written to it. |
| Do files | A saved list of commands, opened with doedit, that makes work repeatable. |
| Command | Purpose |
|---|---|
clear all, set maxvar | Empty the memory and raise the variable limit. |
use, describe, short | Open a dataset and check its size. |
lookfor, codebook | Find variables and read their codes. |
count | Count observations. |
summarize, tabulate | First summaries. |
label list, tabulate, nolabel | See value labels and the codes beneath them. |
save, saveold, use | Write and read Stata datasets. |
import excel, import delimited | Read Excel and text files. |
This part has 10 tasks. The first four need no data: they ask you to name windows and read commands. The rest use Stata. Place the BDHS file and the two practice files in your working folder, write the commands in a do file, run them, and then open the answer to compare.
(a) Command, (b) Results, (c) History, (d) Variables.
summarize v012 v201 if v025 == 2, detailThe command summarize reports summary statistics for the variables v012 and v201, only for observations where v025 equals 2, and the option detail after the comma asks for detailed statistics.
list v001 v002 v012 in 1/10
tabulate v025 v106, rowThe first prints the values of three variables for the first ten observations. The second gives a cross table of v025 and v106 with row percentages.
summarize.StataCourse on your computer, and save the BDHS file in it. In Stata, make it the working folder, confirm the change, and list the files it holds.cd "C:\StataCourse"
pwd
lsThe output of pwd shows the folder, and ls lists the BDHS file. On a Mac the path begins with /Users/ and the name of the user.
doedit, type the three lines below, save the file as session1.do, and run it.* Session 1: practice do file
help summarize
search regressionThe Viewer window opens with the help page and the search results.
clear all
set maxvar 10000
use "BDIR81FL.DTA", clear
describe, shortThe output reports 30,078 observations and 5,425 variables.
lookfor education
codebook v106
list v001 v002 v003 v012 in 1/10
codebook v025
summarize v012 v201 if v025 == 2Check in the codebook that the value 2 carries the label for rural.
bdhs_sample.xlsx. How many observations and variables are there, and which variables are strings?import excel "bdhs_sample.xlsx", sheet("Women") firstrow clear
describe
list in 1/5There are 300 observations and 8 variables. The variables residence, education and wealth are strings.
bdhs_sample.csv, inspect it, and save it as bdhs_sample.dta. Compare the result with the Excel import.import delimited "bdhs_sample.csv", clear
describe
list in 1/5
save "bdhs_sample.dta", replaceThe two imports give the same 300 observations and 8 variables, with the same three string variables.
The next session covers data preparation: creating, recoding and labelling variables, and cleaning and organising datasets.