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
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)
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.