All sessions
1 / 1
Session 2 of 5

Data Preparation: Variable Manipulation and Data Cleaning

Creating, recoding and labelling variables, checking the results and summarising by group, using the BDHS 2022 women's file.

120 minutesLab based exerciseStata 15 or later

Learning objectives

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

  • Select observations and variables with if, keep and drop.
  • Create and change variables with generate, replace and recode.
  • Attach variable labels and value labels to new variables.
  • Check new variables with tabulations and save an analysis file.
Preparation

The data preparation workflow

Raw survey data are rarely ready for analysis. Preparation follows a fixed order, and every step is written in a do file so that it can be repeated.

StepPurposeMain commands
1. OpenLoad only what is neededuse, keep
2. InspectUnderstand the codesdescribe, codebook, tabulate
3. CreateBuild the analysis variablesgenerate, replace, recode
4. LabelMake the output readablelabel variable, label define, label values
5. CheckConfirm each new variable is correcttabulate, summarize, count
6. SaveKeep the result under a new namesave

The raw file is never changed. All work is done in memory and saved under a new name.

Preparation

Starting the session

Begin every do file for this session with the same lines. They empty the memory, raise the variable limit, set the working folder and open the BDHS file.

clear all
set maxvar 10000
cd "C:\StataCourse"
use "BDIR81FL.DTA", clear
describe, short
  • The variables used in this session are listed below.
  • v012 age, v024 division, v025 residence, v106 education level, v133 years of education.
  • v201 children ever born, v501 marital status.
  • v445 body mass index, stored as the index multiplied by 100.
  • Change the folder in cd to your own working folder.
Selecting data

Operators

Conditions and calculations in Stata are built from three groups of operators.

GroupOperatorsMeaning
Arithmetic+ * / ^Add, multiply, divide, power. Subtraction uses the minus key on the keyboard.
Comparison== != > >= < <=Equal, not equal, greater, greater or equal, smaller, smaller or equal
Logical& | !And, or, not

Two signs for equal. A single = assigns a value, as in generate x = 5. A double == tests equality, as in if v025 == 1. Mixing them up produces error r(198) or a wrong result.

Selecting data

Selecting observations with if

The if qualifier restricts a command to the observations for which the condition is true.

count if v025 == 1
summarize v201 if v012 >= 35
tabulate v106 if v025 == 2 & v012 >= 35
  • Conditions can be joined with & for and, and | for or. Use brackets when both appear in one condition.
  • Text values in a condition are placed in quotation marks, as in if city == "Rangpur". Numeric codes are not.
  • A numeric variable with a value label is still tested with its code, so urban is v025 == 1.

Practice

How many urban women are aged 35 or more?
Show solution
count if v025 == 1 & v012 >= 35

The count is 4,428 women.

Selecting data

Keeping and dropping

keep and drop remove variables or observations from the data in memory. They never change the file on disk until the data are saved.

drop v002 v003 v005
keep v001 v012 v024 v025 v106 v133 v201 v445 v501
keep if v012 >= 20
  • keep varlist and drop varlist work on variables.
  • keep if condition keeps the observations that satisfy the condition. drop if condition removes them.
  • Look at the number of observations before and after, using count, to confirm that the right records were removed.

To recover removed data, reopen the dataset with use. For this reason the lines above are not run in the practical exercise unless stated.

Creating variables

Creating a variable with generate

generate creates a new variable from a constant, another variable or an expression. A useful example is the body mass index, BMI.

generate bmi = v445 / 100
summarize bmi
  • The survey stores BMI multiplied by 100, so dividing by 100 gives the usual scale.
  • A new variable needs a name that is not already in use. Stata refuses to overwrite with generate and reports error r(110).
  • Names may contain letters, digits and underscores, and cannot start with a digit. Capital and small letters are different.
  • Common functions include round(), int(), sqrt(), ln() and abs().

Practice

Count the women with a BMI below 18.5. Then create underweight, equal to 1 for these women, and tabulate it.
Show solution
count if bmi < 18.5
generate underweight = 1 if bmi < 18.5
tabulate underweight

There are 1,012 underweight women.

Creating variables

Changing a variable with replace

replace changes the values of a variable that already exists. It is usually paired with generate: first create the variable, then change it for the observations that need a different value.

generate secondary = 0
replace secondary = 1 if v106 >= 2
tabulate secondary v106
  • The first line gives every woman the value 0. The second changes it to 1 where education is secondary or higher.
  • Stata reports how many values were changed. Compare that number with the count expected from the tabulation.
  • The cross tabulation on the last line is the standard check that the new variable agrees with the old one.

Practice

Create secondary, equal to 1 for women with secondary or higher education (v106 of 2 or 3) and 0 otherwise. Check it with a cross tabulation.
Show solution
generate secondary = 0
replace secondary = 1 if v106 >= 2
tabulate secondary v106

The value 1 is expected for 18,054 women.

Creating variables

Recoding with the recode command

recode changes the values of a variable according to rules written in brackets. With the option gen() the original variable is left untouched.

recode v012 (15/19 = 1) (20/24 = 2) (25/29 = 3) (30/34 = 4) (35/39 = 5) (40/44 = 6) (45/49 = 7), gen(agegrp)
tabulate agegrp
recode v201 (0 = 0) (1/2 = 1) (3/max = 2), gen(parity)
tabulate parity
  • Each rule has the form (old = new). A range is written with a slash, as in 15/19.
  • min and max stand for the smallest and largest values, as in (3/max = 3).
  • Values not mentioned in any rule are copied unchanged.
  • The second command groups the number of children into none, one or two, and three or more. It has 3,145, 16,508 and 10,425 women.

Practice

Create agegrp from v012 with seven groups. Which women are in the first group?
Show solution
recode v012 (15/19=1) (20/24=2) (25/29=3) (30/34=4) (35/39=5) (40/44=6) (45/49=7), gen(agegrp)
tabulate agegrp

Group 1 holds the 2,449 women aged 15 to 19.

Labelling

Variable labels

A variable label is a short description of up to 80 characters that appears in output and in the Variables window.

label variable agegrp "Age group of respondent"
label variable parity "Parity group"
label variable secondary "Secondary or higher education"
describe agegrp parity secondary
  • The text goes in quotation marks.
  • Give every new variable a label before saving the file.
Labelling

Value labels in three steps

A value label turns codes into words. It is created once and then attached to one or more variables.

label define parity_lbl 0 "No child" 1 "One or two" 2 "Three or more"
label values parity parity_lbl
tabulate parity
  • label define creates the set of codes and words under a name.
  • label values attaches the named set to a variable. The same set can serve several variables.
  • Add or correct codes later with label define parity_lbl 3 "Other", add or , modify.
  • label list parity_lbl shows the set, and label dir lists all sets in memory.
label define yesno 0 "No" 1 "Yes"
label values secondary yesno

Using one label set such as yesno for all yes and no indicators keeps the output consistent.

Practice

Give a variable label to agegrp and secondary. Create a value label yesno and attach it to secondary. Check with tabulate.
Show solution
label variable agegrp "Age group of respondent"
label variable secondary "Secondary or higher education"
label define yesno 0 "No" 1 "Yes"
label values secondary yesno
tabulate secondary

The tabulation now shows No and Yes in place of 0 and 1.

Labelling

Renaming variables

Clear names make a do file easy to read. Variables can be renamed without changing their values.

rename v012 age
rename v025 residence
rename (v106 v133) (educ educ_years)
describe
  • rename old new changes one name. A bracketed list renames several variables in one command.
  • After renaming, every later command must use the new name.

Practice

Rename v012 to age and v025 to residence, and summarise age. Then restore the original names, because the later commands use them.
Show solution
rename v012 age
rename v025 residence
summarize age
rename age v012
rename residence v025

The mean age is about 32.0 years. Renaming changes only the name, never the values.

Sorting

Sorting and the by prefix

Many commands work within groups of observations. sort orders the rows, and the by prefix repeats a command for each group.

sort v025
by v025: summarize v201
bysort v025: summarize v201
  • by varlist: needs the data sorted on the same variables. bysort sorts and groups in one step.

Practice

Summarise the age of women, v012, separately for each division, v024.
Show solution
bysort v024: summarize v012

Stata prints one table of summary statistics for each of the eight divisions.

Practice

A data preparation do file: opening and creating

All the steps of this session combine into one do file. Run from the top, it rebuilds the analysis file from the raw data at any time.

* Session 2: data preparation
clear all
set more off
set maxvar 10000
cd "C:\StataCourse"

use "BDIR81FL.DTA", clear

* Create variables
recode v012 (15/19=1) (20/24=2) (25/29=3) (30/34=4) (35/39=5) (40/44=6) (45/49=7), gen(agegrp)
generate secondary = 0
replace secondary = 1 if v106 >= 2
recode v201 (0=0) (1/2=1) (3/max=2), gen(parity)
Practice

A data preparation do file: labelling and saving

The second half of the do file labels the new variables, checks them and saves the result.

* Label variables and values
label variable agegrp "Age group of respondent"
label variable secondary "Secondary or higher education"
label variable parity "Parity group"
label define yesno 0 "No" 1 "Yes"
label values secondary yesno
label define parity_lbl 0 "No child" 1 "One or two" 2 "Three or more"
label values parity parity_lbl

* Check
tabulate secondary v106
tabulate agegrp

save "bdhs_prepared.dta", replace
Summary

Key points: data preparation

  • Keep the raw file unchanged, work in a do file and save the result under a new name.
  • Use generate to create and replace to change. Use recode to regroup values.
  • Give every new variable a variable label, and give coded variables a value label.
  • Check each new variable by cross tabulation against its source variable.
Summary

Commands: data preparation

CommandUse
keep, dropRemove variables or observations
generate, replaceCreate and change variables
recodeRegroup values
label variable, label define, label valuesDescribe variables and codes
rename, sortNames and arrangement
tabulate, summarize, countChecks on new variables
saveKeep the prepared data
Exercise

Practical exercises

This part has 5 tasks that bring the commands of the session together. Each topic also has a practice slide in the Slides part. Write the commands in a do file, run them in order, and open the answer after each attempt to compare.

Exercise 1 of 5

Build the analysis file

Write one do file that opens the data and creates agegrp, secondary and parity, labels all of them, checks each one and saves the result as bdhs_prepared.dta.
Show answer
clear all
set maxvar 10000
cd "C:\StataCourse"
use "BDIR81FL.DTA", clear

recode v012 (15/19=1) (20/24=2) (25/29=3) (30/34=4) (35/39=5) (40/44=6) (45/49=7), gen(agegrp)
generate secondary = 0
replace secondary = 1 if v106 >= 2
recode v201 (0=0) (1/2=1) (3/max=2), gen(parity)

label variable agegrp "Age group of respondent"
label variable secondary "Secondary or higher education"
label variable parity "Parity group"
label define yesno 0 "No" 1 "Yes"
label values secondary yesno
label define parity_lbl 0 "No child" 1 "One or two" 2 "Three or more"
label values parity parity_lbl

tabulate agegrp
tabulate secondary v106
tabulate parity

save "bdhs_prepared.dta", replace

The expected counts are 18,054 for secondary.

Exercise 2 of 5

A marital status indicator

Using v501, create married, equal to 1 for women who are currently married (code 1) and 0 for all others.
Show answer
tabulate v501
generate married = 0
replace married = 1 if v501 == 1
label variable married "Currently married"
label values married yesno
tabulate married

The value 1 is expected for 28,537 women and 0 for 1,541 women.

Exercise 3 of 5

Group summaries

Summarise the years of education (v133) separately for urban and rural women.
Show answer
bysort v025: summarize v133

The averages are about 7.76 years in urban and 6.30 years in rural areas.

Exercise 4 of 5

Cross checking two variables

Create large_family, equal to 1 for women with five or more children. Then compare urban and rural women, using v025.
Show answer
generate large_family = 0
replace large_family = 1 if v201 >= 5
tabulate large_family
tabulate large_family v025, column

There are 1,762 women with five or more children. The column percentages show the share of large families in urban and rural areas.

Exercise 5 of 5

Save and reopen

Save the prepared data, close it, open it again, and confirm that the variable labels and value labels remain.
Show answer
save "bdhs_prepared.dta", replace
clear all
use "bdhs_prepared.dta", clear
describe
label list

The labels are saved with the data. Keep the do file, because it documents how every variable was made.

Session 2 complete

Next: Session 3

The next session covers descriptive statistics and graphs: summarising numeric and categorical variables, tables, histograms, box plots and scatter plots.

Continue to Session 3 or return to all sessions.

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