replace: update selected values

Modify an existing variable for a precisely defined subset of observations while leaving every other row unchanged.

Tested 2026-08-06 with the current stats.camp development build · View the do-file on GitHub

Open this example View supported commands

Independent software. Not affiliated with, sponsored by, or endorsed by StataCorp LLC.

Complete example

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)

The example preserves the original write variable and changes only the copy. The missing() condition prevents nonmissing values from being overwritten.

Output from stats.camp

+-------------------------------------------------+
|  #    id    read   write   math   write_filled  |
|-------------------------------------------------|
|  15    15     49             50          49.50  |
+-------------------------------------------------+

How to read the result

Only observation 15 had a missing writing score. Its copied value becomes the average of 49 and 50, or 49.50. The original write column remains missing, which preserves the distinction between observed data and an analyst-created replacement.

This arithmetic replacement is only a teaching device. A real imputation rule needs a defensible model, documentation, and sensitivity checks.

Common qualifiers and mistakes

See the current replace entry and Stata's generate and replace manual for an external reference.

Related guides

Run this exact example

Clone the example repository in stats.camp and open the exact do-file shown on this page. No stats.camp account is required.

Open this example