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 laterBy the end of this session, participants will be able to:
if, keep and drop.generate, replace and recode.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.
| Step | Purpose | Main commands |
|---|---|---|
| 1. Open | Load only what is needed | use, keep |
| 2. Inspect | Understand the codes | describe, codebook, tabulate |
| 3. Create | Build the analysis variables | generate, replace, recode |
| 4. Label | Make the output readable | label variable, label define, label values |
| 5. Check | Confirm each new variable is correct | tabulate, summarize, count |
| 6. Save | Keep the result under a new name | save |
The raw file is never changed. All work is done in memory and saved under a new name.
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, shortv012 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.cd to your own working folder.Conditions and calculations in Stata are built from three groups of operators.
| Group | Operators | Meaning |
|---|---|---|
| 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.
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& for and, and | for or. Use brackets when both appear in one condition.if city == "Rangpur". Numeric codes are not.v025 == 1.count if v025 == 1 & v012 >= 35The count is 4,428 women.
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 >= 20keep varlist and drop varlist work on variables.keep if condition keeps the observations that satisfy the condition. drop if condition removes them.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.
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 bmigenerate and reports error r(110).round(), int(), sqrt(), ln() and abs().underweight, equal to 1 for these women, and tabulate it.count if bmi < 18.5
generate underweight = 1 if bmi < 18.5
tabulate underweightThere are 1,012 underweight women.
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 v106secondary, equal to 1 for women with secondary or higher education (v106 of 2 or 3) and 0 otherwise. Check it with a cross tabulation.generate secondary = 0
replace secondary = 1 if v106 >= 2
tabulate secondary v106The value 1 is expected for 18,054 women.
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(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).agegrp from v012 with seven groups. Which women are in the first group?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 agegrpGroup 1 holds the 2,449 women aged 15 to 19.
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 secondaryA 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 paritylabel 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.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 yesnoUsing one label set such as yesno for all yes and no indicators keeps the output consistent.
agegrp and secondary. Create a value label yesno and attach it to secondary. Check with tabulate.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 secondaryThe tabulation now shows No and Yes in place of 0 and 1.
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)
describerename old new changes one name. A bracketed list renames several variables in one command.v012 to age and v025 to residence, and summarise age. Then restore the original names, because the later commands use them.rename v012 age
rename v025 residence
summarize age
rename age v012
rename residence v025The mean age is about 32.0 years. Renaming changes only the name, never the values.
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 v201by varlist: needs the data sorted on the same variables. bysort sorts and groups in one step.v012, separately for each division, v024.bysort v024: summarize v012Stata prints one table of summary statistics for each of the eight divisions.
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)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", replacegenerate to create and replace to change. Use recode to regroup values.| Command | Use |
|---|---|
keep, drop | Remove variables or observations |
generate, replace | Create and change variables |
recode | Regroup values |
label variable, label define, label values | Describe variables and codes |
rename, sort | Names and arrangement |
tabulate, summarize, count | Checks on new variables |
save | Keep the prepared data |
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.
agegrp, secondary and parity, labels all of them, checks each one and saves the result as bdhs_prepared.dta.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", replaceThe expected counts are 18,054 for secondary.
v501, create married, equal to 1 for women who are currently married (code 1) and 0 for all others.tabulate v501
generate married = 0
replace married = 1 if v501 == 1
label variable married "Currently married"
label values married yesno
tabulate marriedThe value 1 is expected for 28,537 women and 0 for 1,541 women.
v133) separately for urban and rural women.bysort v025: summarize v133The averages are about 7.76 years in urban and 6.30 years in rural areas.
large_family, equal to 1 for women with five or more children. Then compare urban and rural women, using v025.generate large_family = 0
replace large_family = 1 if v201 >= 5
tabulate large_family
tabulate large_family v025, columnThere are 1,762 women with five or more children. The column percentages show the share of large families in urban and rural areas.
save "bdhs_prepared.dta", replace
clear all
use "bdhs_prepared.dta", clear
describe
label listThe labels are saved with the data. Keep the do file, because it documents how every variable was made.
The next session covers descriptive statistics and graphs: summarising numeric and categorical variables, tables, histograms, box plots and scatter plots.