Command reference

replace — change values in an existing variable

Update an existing variable using an expression. Combine replace with a condition to change selected observations while keeping all other values as they are.

Syntax

replace variable = expression [if condition] [in first/last]

variable is the column to update; it must already exist. The expression can refer to that column or to other variables. For example, replace score = score + 5 if group == 1 adds five only for observations in group 1.

Selecting values to change

if condition
Update only observations satisfying the condition. For example, if missing(score) selects missing values, and if group == 1 selects one group. Omit the qualifier to update every observation.
in first/last
Restrict the assignment to positions in the current row order, such as in 1/10. When combined with if, an observation must satisfy both restrictions.
by group: or bysort group:
Evaluate group-dependent expressions within each group. bysort also sorts the data; by requires the relevant ordering. Within a group, _n and _N refer to its observation positions and size.

Example

The sample copies writing scores into write_filled, then fills the missing value with the mean of that student’s reading and math scores. It lists only the student whose original writing score was missing.

clear
import delimited "data/student_scores.csv"
generate write_filled = write
replace write_filled = (read + math) / 2 if missing(write_filled)
list id read write math write_filled if missing(write)
Open example in browser

Sample data included. Opens in a new tab; click Run.

What to look for

Student 15 has reading 49 and math 50, so write_filled becomes 49.5. The original write remains missing, and every other copied writing score stays unchanged. This illustrates a conditional replacement; whether this fill rule is suitable for an analysis depends on why the score is missing.