Stata技术问询:交互式执行preserve后,ado文件嵌套使用是否有效?
Can Nested
preserve/restore Work in Stata When Calling an ADO File? Great question! Let’s break this down clearly, since there’s a common misconception about Stata’s preserve/restore limitations.
Short Answer
Yes, nested use of preserve and restore (interactive preserve + an ADO file with its own preserve/restore pair) works perfectly as intended.
Why This Works
Stata uses a stack-based system for preserve/restore, not a single one-time storage slot:
- Every
preservecommand saves the current in-memory dataset state to a temporary file and pushes it onto a stack. - A default
restorepops the most recent state off the stack and restores it, leaving earlier preserved states untouched.
This means nested calls don’t interfere with each other—each preserve adds a new layer to the stack, and each restore only undoes the most recent layer.
Example Walkthrough
Let’s make this concrete with code:
1. Interactive Session Setup
sysuse auto, clear // Load sample dataset preserve // Save the original auto dataset state to the stack replace price = price * 2 // Modify price in interactive mode list make price in 1/3 // Verify price is doubled
2. Your Custom ADO File (mymodify.ado)
program define mymodify preserve // Push the current interactive state (doubled price) onto the stack replace mpg = mpg * 2 // Modify mpg inside the ADO list make price mpg in 1/3 // Show temporary modified state restore // Pop the ADO's preserved state, reverting to doubled price (mpg back to original) end
3. Run the ADO in Interactive Mode
mymodify // Executes the ADO: you'll see mpg doubled temporarily, then reverted list make price mpg in 1/3 // Back to the interactive state (price doubled, mpg original) restore // Pop the initial interactive preserve, reverting to the original auto dataset list make price in 1/3 // Price is back to original values
Key Notes
- If you omit
restorein your ADO, the stack will retain that extra state. You’ll need an additionalrestorein the interactive session to get back to your initial preserved state. - Use
restore, notto skip restoring the most recent state (if you want to keep it), orrestore, allto clear the entire stack and revert to the first preserved state.
内容的提问来源于stack exchange,提问作者FalafelPita
相关产品推荐
相关产品推荐

