Stata preserve/restore and tempvar: Safe Data Manipulation Patterns
preserve and restore let you make destructive changes safely. tempvar and tempfile prevent namespace pollution. Here are the patterns every do-file needs.
You need a temporary collapse or merge, but one wrong step could overwrite the only in-memory version of your cleaned dataset.
You will apply safe transformation patterns that let you test operations without risking irreversible data loss.
All examples tested in Stata 18 SE. Compatible with Stata 15+.
Quick Answer
- Use preserve before destructive operations.
- Restore as soon as temporary computation is complete.
- Use tempvar/tempfile for intermediate objects in reusable scripts.
- Avoid hard-coded temporary variable names.
Make Destructive Steps Reversible by Default
Wrap destructive transforms with preserve and restore
Analytic scripts often need temporary subsetting or aggregation. preserve/restore provides a transaction-like pattern for these operations.
This keeps your main dataset intact while still enabling intermediate computations.
If you are extending this pipeline, also review Export Regression Tables in Stata and Clustered Standard Errors in Stata.
1clear all2set obs 12003gen firm_id = ceil(_n/12)4gen year = 2014 + mod(_n,10)5gen wage = 18 + rnormal(0,4)6gen education = 8 + floor(runiform()*10)78count9preserve10 keep if year >= 201811 collapse (mean) mean_wage=wage mean_edu=education, by(year)12 list year mean_wage mean_edu13restore14count1200
Use tempvar and tempfile to prevent namespace collisions
Reusable do-files and programs fail when temporary variable names clash with existing columns. tempvar prevents this by generating safe names.
tempfile is equally useful when temporary disk artifacts are needed across commands.
1clear all2set obs 12003gen firm_id = ceil(_n/12)4gen year = 2014 + mod(_n,10)5gen wage = 18 + rnormal(0,4)6gen education = 8 + floor(runiform()*10)78count9preserve10 keep if year >= 201811 collapse (mean) mean_wage=wage mean_edu=education, by(year)12 list year mean_wage mean_edu13restore14count1516* ---- Section-specific continuation ----17tempvar z_wage18quietly summarize wage19gen `z_wage' = (wage - r(mean)) / r(sd)2021tempfile subset22preserve23 keep firm_id year `z_wage'24 save `subset'25restore2627use `subset', clear28describeContains data from /var/folders/.../ST_00001.tmp Observations: 1,200 Variables: 3
Common Errors and Fixes
"nothing to restore"
restore was called without an active preserved dataset state.
Ensure preserve is executed in the same run path before restore.
nothing to restore r(622);
restorepreservekeep if year>=2018restore1capture noisily preserve2keep if year>=20183restore. restore
Command Reference
preserve / restore / tempvar
Stata docs โSupports reversible dataset operations and collision-safe temporary objects.
preserveSaves in-memory dataset staterestoreRestores preserved statetempvarCreates guaranteed-unique temporary variable namestempfileCreates temporary file handles for disk-backed stepsHow Sytra Handles This
Sytra can wrap risky transformations with preserve/restore and manage tempvar/tempfile lifecycle automatically.
A direct natural-language prompt for this exact workflow:
Wrap a temporary collapse and subset operation with preserve/restore, use tempvar for standardized wage, save an intermediate tempfile, then restore original data and verify row count unchanged.Sytra catches these errors before you run.
Sytra can wrap risky transformations with preserve/restore and manage tempvar/tempfile lifecycle automatically.
Join the Waitlist โFAQ
When should I use preserve and restore?
Use them around destructive operations like collapse, keep/drop, or temporary merges when you need to return to the original dataset state.
Why use tempvar instead of regular variable names?
tempvar avoids naming collisions in reusable programs and automatically cleans up after execution.
Can I nest preserve calls?
Stata supports one active preserved dataset at a time; nested preserve logic needs careful sequencing or tempfiles.
Related Guides
- Stata Macros: local, global, and Extended Functions Explained
- Stata Loops: foreach and forvalues Tutorial with 20 Practical Examples
- Linked Datasets in Stata: frlink/frget Workflows Instead of Repeated Merges
- How to Structure a Stata Project: Directory Layout, Naming, and Automation
- Explore the workflow pillar page
- Open the full workflow guide index
- Browse all Stata & R guides on the blog index
- Browse all Stata pillars
We build practical, reproducible workflows for Stata and R teams working on real empirical research pipelines.