Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Data Management

Generating and Replacing Variables

Create and change variables in Stata with generate, replace, egen, recode, cond() and rename. Learn the safe pattern for conditional variables and how to handle missing values.

Raw data is rarely ready for analysis. You will compute ratios, build indicator variables, group ages into bands and fix wrong values. In Stata, nearly all of this is done with four commands: generate, replace, egen and recode. This lesson shows each one and, just as important, the habits that prevent mistakes with conditions and missing values.

generate: make a new variable

STATA
generate bmi = weight / (height^2)
generate logincome = ln(income)
generate agesq = age^2
generate str6 id6 = string(id, "%06.0f")    // text with leading zeros
gen byte adult = (age >= 18) if !missing(age)

generate (shortened gen) creates one new variable whose value is computed for every observation. If the name already exists, Stata refuses: variable bmi already defined (r(110)). It is a feature: you cannot overwrite a variable by accident. Use replace to change an existing one, or drop it first.

Expressions can use arithmetic (+ - * / ^), comparison, logical operators and many functions:

Group Examples
Math abs(), sqrt(), ln(), exp(), round(x, 0.01), floor(), ceil(), mod(x, y)
String upper(), lower(), trim(), substr(), strpos(), length(), regexm()
Date date(), year(), month(), mdy(), dow()
Logic inlist(x, 1, 2, 3), inrange(x, 10, 20), missing(x), cond()

You can specify the type to save memory: gen byte, gen int, gen double, gen str20.

Logical expressions give 0 and 1

A comparison in Stata evaluates to 1 (true) or 0 (false). That yields a one-line way to make an indicator:

STATA
generate byte senior = (age >= 65)

But remember that a missing age is "larger than any number", so it would get senior = 1. Add the missing guard:

STATA
generate byte senior = (age >= 65) if !missing(age)

replace: change an existing variable

STATA
replace income = income / 1000          // rescale in place
replace region = "North" if region == "N"
replace income = . if income < 0

replace has no "are you sure" step, so work carefully: it modifies the data in memory immediately. A good habit is to run count if <condition> first to see how many observations will change, and to run replace only from a do-file, so the exact step is recorded and the original data can be reloaded.

The two-step pattern for conditional variables is the most common recipe:

STATA
generate agegroup = .
replace agegroup = 1 if age < 30
replace agegroup = 2 if age >= 30 & age < 50
replace agegroup = 3 if age >= 50 & !missing(age)

Start from missing, then fill every case you intend. Afterward, tabulate agegroup, missing should have no unexpected missing values. A single-line alternative uses cond():

STATA
generate agegroup2 = cond(age < 30, 1, cond(age < 50, 2, 3)) if !missing(age)

cond(condition, if_true, if_false) is compact but gets hard to read when nested more than two levels; prefer the replace pattern for clarity.

egen: generate with group and summary functions

egen ("extended generate") offers functions that work across observations or across variables:

STATA
egen mean_income = mean(income)                  // overall mean, same for every row
egen region_mean = mean(income), by(region)      // mean within each region
egen rowmean_score = rowmean(q1 q2 q3)           // across variables, skipping missing
egen total_score = rowtotal(q1 q2 q3)            // sum across variables, missing as zero
egen age_cat = cut(age), at(0, 18, 40, 65, 120)  // bins
egen id_group = group(region year)               // a numeric id for each combination
egen n_in_group = count(income), by(region)      // non-missing observations per region
egen rank_inc = rank(income)                     // rank

Remember: generate works observation by observation (one row at a time), while egen can see the whole column or group. You can see the same logic with bysort region: egen ... in the by-prefix lesson (sort and by). Note that egen options go after the comma: by(...).

recode: change values using a rule list

STATA
recode age (0/17 = 1 "Child") (18/64 = 2 "Adult") (65/max = 3 "Senior"), generate(agecat)
recode rating (1 2 = 1) (3 = 2) (4 5 = 3)    // collapse five values to three
recode q1-q5 (-9 = .a) (-8 = .b)             // survey codes to missing, many variables
recode score (min/0 = 0)                     // floor at zero
  • Rules are written (old values = new value), with ranges a/b and the keywords min, max, missing, nonmissing.
  • generate(newvar) creates a new variable. Without it, recode overwrites the original, which is rarely what you want.
  • A label in the rule ("Adult") creates value labels automatically.

Dropping, keeping and renaming

STATA
drop age2 age3              // remove variables
drop if missing(id)         // remove observations
keep id age income          // keep only these variables
keep if year >= 2010        // keep only these observations
rename income monthly_inc   // rename a variable
rename (a b c) (x y z)      // several at once
rename *_2023 *_y2023       // pattern rename
order id year, first        // move columns to the front

drop and keep are two sides of the same choice: use whichever lists fewer names. Never drop rows to "fix" a problem you have not diagnosed: count them first.

Naming conventions

Names can have up to 32 characters (letters, digits, underscores; must start with a letter or underscore; case-sensitive). Use lowercase snake_case, name indicator variables for what they mean (female, urban), and avoid names that collide with commands.

Stand-in: the replace pattern

The Python model below builds an age group the same way the do-file does: start with missing, fill in conditions in order, and count the result.

Python Stand-in: generate, then replace with conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in: egen mean by group

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every row of a region receives the same group mean, including the row whose income is missing. That is exactly how egen ..., by() fills the new variable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if you run generate age = 5 when age already exists?

    generate never overwrites; use replace to change an existing variable.
  2. 2. Why add if !missing(age) to generate old = (age >= 65)?

    Without the guard, missing ages would be coded as old.
  3. 3. What does egen mean_inc = mean(income), by(region) produce?

    egen with by() fills each observation with the statistic of its group.
  4. 4. What does recode do without the generate() option?

    Without generate(newvar), recode changes the existing variable in place.

Summary

  • generate creates variables, replace changes them, drop and keep remove columns or rows.
  • A comparison evaluates to 1 or 0; guard against missing with if !missing(x).
  • Start conditional variables with . and then replace ... if ... for each case, then check with tabulate, missing.
  • egen gives group and row-wise functions; recode maps value lists; always use generate() with it.
  • Use readable lowercase names and keep every change in a do-file.

Next: Conditions and Logical Operators