Liz's Stata Guide

Commands: Variables

This page covers commands for dealing with variables -- making new ones, deleting them, changing how they are stored, coded, labeled and named.

generate
Creates a new variable.
gen newvar = (varx > 50) if varx < .   - or -
gen newvar = 10 * varx + vary   - or -
tab varx, gen(newvar_)

egen
Creates a new variable using various nifty functions.
egen bigvar = rmax(varx vary varz)

replace
Modifies some or all the values of an existing variable.
replace varx = varx * 12     - or -
replace varx = 10 if vary > 0

drop; keep
Retain only certain variables or observations from the dataset.
drop varx   - or -
keep vary varz   - or -
drop if vary < 0

recode
Alters the coding of a category variable or creates a category variable from a continuous one.
recode varx (1 = 1) (2 = 0) (else = .)   - or -
recode vary (0/5 = 1 "low") (6/10 = 2 "mid") (10/20 = 3 "high"), gen(ylev)

encode; destring
Converts a string variable that contains numbers (use destring) or categories (use encode).
encode varx, gen(newvar)
destring varx, replace

label variable; label define; label values
Attaches labels to variables and values of variables.
label variable varx "Variable X"
label define groups 1 big 2 medium 3 small
label values varx groups

rename
Changes the name of a variable.
rename vsrx varx   - or -
rename hh_q(##)a x(#)

contact: djiboliz@gmail.com
last modified: 31 July 2014