To keep a variable's values intact while you run other commands in Stata, the core move is to prevent commands from dropping observations, replacing the variable, or reordering your data without your knowledge. In most cases you do that by saving a snapshot first (preserve or save), and by choosing commands that don't silently delete rows—most commonly using replace instead of a second generate, and adding if conditions so missing-data edits don't wipe valid values. The small, easy checks near the end of each step tell you whether the variable actually survived.
The phrase "maintain a variable in Stata upon" gets used loosely. It can mean "keep it after a merge," "hold a constant value across a reshape," "carry it forward through a loop," or "protect it while cleaning." The ordered steps below cover the maintenance workflow that handles all of these, then the later sections isolate the specific traps: merges, reshapes, loops, missing values, and labels.
Step 0: Know What "Maintain" Means for Your Data
Before touching anything, identify three things about the variable you want to keep:
Its type and storage. Run describe varname and codebook varname. Is it numeric or string? What's its storage type (byte, int, long, float, double, str#)? A reshape or merge can't change type under most commands, but a recode or destring can. Whether it's the sort/ID variable. If the variable is your unique identifier, it must be unique and nonmissing, or a merge will duplicate or drop rows. What could destroy it. The typical killers are drop, keep, clear, collapse, bysort ... : keep if _n==1, a second generate (which errors, not deletes—so it's safer than people think), and merge with update or replace.
A quick diagnostic is isid varname for ID variables and assert !missing(varname) if the variable must always be populated. Both fail loudly when the assumption breaks, which is the point.
Step 1: Snapshot Before You Touch Anything
The most reliable maintenance technique is not clever syntax—it's reversibility. You have two tools:
Option A: preserve / restore (in-memory, fast, stack-limited).
preserve copies the current dataset in memory to a temporary area. Any command that alters the data is undone by restore. It's the right tool for a single exploratory move: test a merge, check the result, restore, then commit if it's right.
Option B: save a versioned file (durable, survives a crash).
The tradeoff is disk and a reload cost, but it's the safer habit for long sessions and for anything you'll revisit. The success check for either: after restoring, run count and summarize varname and confirm identical N, mean, min, and max to what you recorded before.
Step 2: Change Values with replace, Never with a Second generate
This is the single most common way people lose a variable: they expect generate to overwrite, and it doesn't. A second generate on an existing name fails with "variable already defined." That error is protective—take it as a signal to use replace.
If you must rebase or transform values but want the original for comparison, create a shadow copy first:
clonevar preserves the variable's labels and value labels, which generate score_orig = score does not always carry over cleanly. Now you can always compare score score_orig to see exactly what changed.
Step 3: Scope Every Edit with if, in, or bysort
Unrestricted replace statements are where valid values quietly disappear. Scope each one:
For group-level maintenance, bysort keeps the group structure while editing:
That last example carries the last valid value forward within each household—a maintain-through-fill pattern. The check: after any replace, run assert on what you intended to leave untouched. For instance, assert wage == wage_orig if year != 2025 catches collateral damage immediately.
Step 4: Protect the Variable Through a Merge
Merges are the biggest source of "where did my variable go" complaints, for two reasons: unmatched rows can be dropped, and same-named variables from the using file can overwrite the master's values.
Rules that maintain your variable:
Use keep(master match) or keep(match) when you don't want unmatched master rows dropped. The default merge keeps all master rows, but keepusing and manual merging often don't. Watch name collisions. If both files have income, Stata's merge keeps the master's value where both are nonmissing and takes the using file's where the master is missing—unless you specify update. If you want the master to win outright, rename the using variable before merging: rename income income_using in the using file. Check uniqueness before you merge. Run isid id on both files. A non-unique key produces a many-to-many merge, which duplicates rows and makes your variable's row count balloon.
The success check after a merge: count if _merge == 1 etc., and assert !missing(varname) on the population where it should be present. Confirm that N matches the merge report.
Step 5: Carry the Variable Through a Reshape
reshape moves data between wide and long layouts. A variable you want "maintained" across a reshape must be part of the i() (identifier) variables, or it will be broadcast and then possibly dropped as redundant.
Here studentid—the maintained identifier—appears in every long-format row. Any constant character like school gets repeated automatically if it varies only by i(). If your variable varies by wave, it must be a stub: score1 score2 score3 become score with j(wave).
The trap: if you reshape and a non-identifier, non-stub variable exists, Stata will complain or replicate it, and a later reshape wide can only reconstruct one copy. The check: reshape, then run reshape wide back and confirm the dataset matches the original with cf (compare files) or a saved copy.
Step 6: Maintain Variables Inside Loops and Programs
In a foreach/forvalues loop, a variable can be overwritten on each iteration—if that's intended, fine; if not, you need a suffix or a store.
Alternatively, accumulate results in a matrix or a separate file:
In ado-programs, use tempvar for scratch variables so you never clobber the caller's data:
The check: after the loop, describe shows the variables you expected and no surprises; if the loop wrote to disk each iteration, compare the first and last saved file.
Step 7: Handle Missing Values Explicitly
Missing-value logic is a maintenance killer because Stata treats "." (numeric missing) as larger than any real number in comparisons. So replace x = 0 if x > 100 will not touch missings, but replace x = 0 if x < 100 silently converts missings to zero if you're not careful with string-to-numeric gaps.
Rules:
Use missing() in conditions, not equality: if missing(x). For extended missing values (.a, .b), missing() returns true; x == . does not. Before transforming, assert x == . if !missing(x) as a sanity pattern, or count if missing(x).
An example of a safe recode that maintains the original where it exists:
Step 8: Preserve Labels and Metadata
Values can be intact while the variable becomes unusable because labels vanished. save keeps labels; certain imports and collapse do not. To maintain, verify:
If you rebuild a variable, carry metadata forward explicitly:
clonevar copies labels; plain generate does not. This matters most when the maintained variable feeds a table or graph later, where an unlabeled variable looks like a raw number.
Step 9: Verify the Variable Survived
A repeatable end-of-step check is faster than intuition. A compact pattern:
Or compare a saved copy:
If every row matches and only the expected variables differ, the variable was maintained. If assert(match) fails, you know exactly which IDs changed.
Common Failure Modes and What They Mean
Each symptom below points to a specific cause and a reversible first check:
| Symptom | Likely cause | First check |
|---|---|---|
| Variable gone entirely | drop or keep without including it | describe, then restore if you preserved |
| Rows multiplied | Non-unique merge key | isid id on both files |
| Valid values became missing | Unscoped replace or structural missing recode | count if missing(varname); compare to varname_orig |
| Type changed (string to numeric) | destring or recast | describe varname |
| Labels vanished | merge, collapse, import | label list; rebuild with clonevar |
| Value differs only in some groups | bysort scope mismatch | bysort group: assert ... |
Start with reversible checks (preserve/restore, save/use) before attempting repair. If a step requires reformatting raw files you didn't create or repairing an already-corrupted dataset that came from a third party, save a copy and treat the original as read-only until you've confirmed the fix on a copy.
Where Professional Help Makes Sense
Stata maintenance is usually low-risk, but two situations warrant stopping for help: a dataset you didn't build whose provenance and structure you can't verify, and any operation that touches regulated or protected data (health records, personally identifying files) where a misstep could cause disclosure. In those cases, preserve the raw file, document every command in a do-file, and have someone with knowledge of the original data structure confirm the plan before you commit changes.
FAQ
Does preserve have a size limit? It's bounded by memory and the maxvar/stack settings, not by disk. For very large datasets, saving to a .dta file is the more scalable snapshot.
Can I maintain a variable across separate Stata sessions? Only through saved files. In-memory objects vanish when Stata closes. Version your .dta snapshots with dated filenames.
Why did merge drop my master rows? It didn't, by default. merge keeps all master observations unless you specify keep(match) or similar. If rows vanished, a preceding drop or a keepusing mismatch is the more likely cause.
Is there a way to lock a variable against changes? Stata has no per-variable write protection, but do-file discipline (clone, check, commit) plus assert statements gives you equivalent protection.