All sessions
1 / 1
Session 1 of 5

Stata Environment, Opening Data and Importing

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 later

Learning objectives

By the end of this session, participants will be able to:

  • Identify the main windows of Stata and state the purpose of each.
  • Read a Stata command and recognise common error messages.
  • Use the help system, set the working folder and run a do file.
  • Open the BDHS dataset and inspect it with basic commands.
  • Distinguish numeric and string variables, and use labels correctly.
  • Import Excel and CSV files and save the data in Stata format.
Introduction

What Stata is

Stata is a statistical package for data management, analysis, graphics and reporting. It is used widely in public health, economics and the social sciences.

  • Work is command driven. Menus exist, but every action corresponds to a typed command that can be saved and repeated exactly.
  • Stata holds one dataset in memory at a time, and every command acts on that dataset.
  • Stata is available in editions (BE, SE and MP) that differ mainly in data size and speed. The commands taught here work in all of them.
Introduction

Working conventions for this course

  • All commands in this course run in Stata 15 and later.
  • Commands and variable names are case sensitive. The command summarize exists, but Summarize does not.
  • Code appears in light panels. Each panel has a Copy button, and the text may be pasted into the Do file Editor.
  • Menu names and window titles can differ slightly between versions. The typed commands do not.
Introduction

The dataset: Bangladesh Demographic and Health Survey 2022

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.

  • File name: BDIR81FL.DTA, in Stata format.
  • The file contains 30,078 women and 5,425 variables. Variable names follow the DHS coding scheme, such as 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.

Introduction

Variables used in the course

VariableMeaning
v001, v002, v003Cluster number, household number and respondent line number. Together they identify a woman.
v005Women's sample weight, used in later sessions.
v012Current age of the respondent, in years.
v024Region, that is, the division of residence.
v025Type of place of residence: urban or rural.
v106Highest level of education attained.
v190Wealth index, in five groups.
v201Total number of children ever born.

Survey weights are introduced after the basic tools are in place, so early summaries are unweighted.

Introduction

The default Stata layout

Toolbar: open, save, do file editor, data editor, data browser HistoryCommands already run ResultsOutput and error messages VariablesNames in the dataset PropertiesLabel, type and format CommandType one command here and press Enter
Introduction

What each window does

WindowPurpose
CommandWhere a single command is typed and executed with Enter.
ResultsDisplays output, including error messages.
HistoryLists commands run in the session. Older versions call it Review. A double click runs a command again.
VariablesLists the variables of the dataset in memory. Clicking a name pastes it into the Command window.
PropertiesShows the label, type and format of the selected variable.
Introduction

Windows that open on request

  • Do file Editor: where scripts of commands are written and run.
  • Data Browser (browse): displays the data without allowing changes.
  • Data Editor (edit): displays the data and allows changes.
  • Viewer: shows help pages.
  • Graph window: shows charts produced by graph commands.

Browse before you edit. A stray keystroke in the Data Editor can alter a value. Use the Data Browser unless editing is intended.

Introduction

Entering data in the Data Editor

Small tables can be typed directly into the Data Editor, without writing any command.

  • Open the Data Editor from the toolbar.
  • Click the first cell and type a value. Use Tab to move across and Enter to move down.
  • Stata names the columns var1, var2 and so on. Select a variable and change its name and label in the Properties window.
  • A column that holds only numbers becomes a numeric variable. A column that holds text becomes a string variable.

Typing suits very small tables. Larger data should be imported from a file, which is covered later in this session.

Syntax and help

The general form of a command

Most Stata commands follow one pattern. Everything after the command name is optional.

commandwhat to do
varlistwhich variables
ifwhich observations, by condition
inwhich observations, by position
, optionshow to do it
Syntax and help

Reading a command

summarize v012 v201 if v025 == 2, detail

This asks Stata to summarise the variables v012 (age) and v201 (children ever born), only for observations where v025 equals 2, with detailed statistics.

  • A double equals sign tests a condition. A single sign assigns a value.
  • The comma separates the options from the rest of the command.
  • The code for rural is shown for illustration. Confirm the codes of a variable with codebook v025 before relying on them.
Syntax and help

Useful rules

  • Commands and variable names are case sensitive, and are normally written in lower case.
  • Many commands have abbreviations, for example sum for summarize. This course writes commands in full for clarity.
  • A prefix repeats a command for each group, for example bysort v025: summarize v012.
  • If a command is wrong, Stata prints a message in red together with a return code such as r(199). Nothing is changed in the data.
Syntax and help

Common error messages

MessageCodeUsual cause
unrecognized commandr(199)Misspelt command, or wrong case such as Summarize.
variable not foundr(111)Misspelt variable name, or no dataset loaded.
file not foundr(601)Wrong file name, or the wrong working folder.
no; dataset in memory has changed since last savedr(4)Loading another dataset without the clear option.
no room to add more variablesr(900)The dataset has more variables than the limit set by maxvar. Raise the limit with set maxvar.
Syntax and help

Getting help

* 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 outreg2

Help 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.

Working folder

The working folder

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
ls

Replace the example paths with a folder on your computer, place the BDHS file in it, and confirm with pwd and ls.

Do files

Do files

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.

  • Open the editor from the toolbar, from the menu, or by typing doedit.
  • Save the file with the extension .do.
  • Run it with the Execute (do) button, or press Ctrl+D on Windows and Cmd+Shift+D on a Mac. If lines are selected, only those lines run.
Do files

Comments

StyleUse
* textA comment on its own line, with the asterisk at the start.
// textA 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.

Opening a dataset

Raising the variable limit with set maxvar

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 10000
  • clear 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/SE allows up to 32,767 variables, and Stata/MP allows more. Stata/BE is fixed at 2,048 variables and cannot be changed.

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", clear
Opening a dataset

Opening the BDHS dataset

clear all
set maxvar 10000
use "BDIR81FL.DTA", clear
describe, short
  • The first two lines raise the variable limit, as explained on the previous slide.
  • use 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.

Opening a dataset

Finding variables in a large dataset

lookfor education
lookfor wealth
codebook v106
  • lookfor 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.
Opening a dataset

Looking at observations

count
count if v025 == 2
  • count reports the number of observations, optionally those meeting a condition.
Opening a dataset

First summaries

summarize v012 v201
tabulate v025
tabulate v106
tabulate v025 v106, row
  • summarize 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.

Structure

Two kinds of variable

KindHoldsExamples in the BDHS file
NumericNumbers, including coded categoriesv012 age, v201 children ever born, v025 residence (coded 1 and 2)
StringText of any kindNames, 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.

Working with the BDHS file

Variable labels and value labels

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, nolabel
  • The name of the value label is shown in the describe output. In this file the labels are named in capitals, such as V025.
  • label list prints the codes and their words.
  • The nolabel option shows the underlying numeric codes instead of the words.
Saving data

Saving and reopening a dataset

save "mydata.dta", replace
use "mydata.dta", clear
  • save writes the dataset in memory to a .dta file. Without replace, Stata refuses to overwrite an existing file of the same name.
  • Saving under a new name keeps the original file safe. Never save over the raw data file.
  • A colleague using an older version of Stata may need saveold "mydata.dta", replace, which writes a copy that older versions can read.
Importing

Practice files for importing

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.

FileContents
bdhs_sample.xlsxExcel workbook with a sheet called Women holding the data and a sheet called Notes describing the columns.
bdhs_sample.csvThe same data as plain text, with commas between values.

Download both files from the course folder and save them in the working folder.

Importing

Importing an Excel file

import excel "bdhs_sample.xlsx", sheet("Women") firstrow clear
describe
list in 1/5
  • sheet() 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.
  • To read only part of a sheet, add cellrange(A1:H301).
Importing

Importing a CSV file

import delimited "bdhs_sample.csv", clear
describe
list in 1/5
  • import delimited reads text files whose values are separated by commas, tabs or another character.
  • Stata uses the first row as variable names when it looks like a header.
  • Add delimiter(";") if the separator is not a comma.
Do files

A standard do file template

* 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 v106

The structure matters most: clear the workspace, set the folder, open the data, then do the work.

Summary

Key points: the working environment

TopicRemember
WindowsCommand to type, Results to read, History to repeat, Variables and Properties to inspect the data.
Syntaxcommand, then varlist, then if or in, then a comma and options.
CaseCommands and variable names are case sensitive and usually lower case.
ErrorsA message and a return code appear in red, and the data are not changed.
Helphelp for a known command, search for a topic.
Working folderpwd shows it, cd changes it, and files are read from it and written to it.
Do filesA saved list of commands, opened with doedit, that makes work repeatable.
Summary

Commands: opening and importing data

CommandPurpose
clear all, set maxvarEmpty the memory and raise the variable limit.
use, describe, shortOpen a dataset and check its size.
lookfor, codebookFind variables and read their codes.
countCount observations.
summarize, tabulateFirst summaries.
label list, tabulate, nolabelSee value labels and the codes beneath them.
save, saveold, useWrite and read Stata datasets.
import excel, import delimitedRead Excel and text files.
Exercise

Practical exercises

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.

Exercise 1 of 10

Name the window

Which window would you use to (a) type a command, (b) read the output, (c) see the commands already run, and (d) see the names of the variables?
Show answer

(a) Command, (b) Results, (c) History, (d) Variables.

Exercise 2 of 10

Read a command

Explain each part of this command: what it does, to which variables, for which observations, and with which option.
summarize v012 v201 if v025 == 2, detail
Show answer

The 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.

Exercise 3 of 10

Read two more commands

Explain what each of these commands asks Stata to do.
list v001 v002 v012 in 1/10
tabulate v025 v106, row
Show answer

The 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.

Exercise 4 of 10

Interpret the errors

Give the likely cause of each message, and say how it would be corrected.
  • unrecognized command: Summarize, r(199)
  • variable v02 not found, r(111)
  • file BDIR81FL.DTA not found, r(601)
Show answer
  • The command was typed with a capital letter. Write it as summarize.
  • The variable name is misspelt. Check the name in the Variables window.
  • The file name is wrong, or the working folder is not the folder that holds the file. Correct the name or the folder.
Exercise 5 of 10

Set the working folder

Create a folder called 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.
Show answer
cd "C:\StataCourse"
pwd
ls

The 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.

Exercise 6 of 10

Write a first do file

Open the Do file Editor with doedit, type the three lines below, save the file as session1.do, and run it.
Show answer
* Session 1: practice do file
help summarize
search regression

The Viewer window opens with the help page and the search results.

Exercise 7 of 10

Open the data

Raise the variable limit to 10,000, open the BDHS file from your working folder, and check how many observations and variables it contains.
Show answer
clear all
set maxvar 10000
use "BDIR81FL.DTA", clear
describe, short

The output reports 30,078 observations and 5,425 variables.

Exercise 8 of 10

Find and inspect

Find the variables that refer to education and show the coded values of the highest educational level. List the identifiers and age of the first ten women, then summarise age and children ever born for the rural women, after confirming the code for rural.
Show answer
lookfor education
codebook v106
list v001 v002 v003 v012 in 1/10
codebook v025
summarize v012 v201 if v025 == 2

Check in the codebook that the value 2 carries the label for rural.

Exercise 9 of 10

Import the Excel file

Import the sheet called Women from bdhs_sample.xlsx. How many observations and variables are there, and which variables are strings?
Show answer
import excel "bdhs_sample.xlsx", sheet("Women") firstrow clear
describe
list in 1/5

There are 300 observations and 8 variables. The variables residence, education and wealth are strings.

Exercise 10 of 10

Import the CSV file

Import bdhs_sample.csv, inspect it, and save it as bdhs_sample.dta. Compare the result with the Excel import.
Show answer
import delimited "bdhs_sample.csv", clear
describe
list in 1/5
save "bdhs_sample.dta", replace

The two imports give the same 300 observations and 8 variables, with the same three string variables.

Session 1 complete

Next: Session 2

The next session covers data preparation: creating, recoding and labelling variables, and cleaning and organising datasets.

Continue to Session 2 or return to all sessions.

Use the left and right arrow keys. Press F for full screen.