replace: update selected values
Modify an existing variable for a precisely defined subset of observations while leaving every other row unchanged.
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
replacehas no general-purpose safety option; useiforinto state the target rows explicitly.- Count or list the target observations before replacing values, then verify the same subset afterward.
- The expression must have the same broad type as the destination: numeric expressions for numeric variables and string expressions for string variables.
- Official Stata can cascade replacements that refer to preceding observations. stats.camp currently evaluates expressions against the pre-command data, so it does not reproduce that cascade.
- Create a copy first when the original measurement should remain auditable.
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