You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 preserve command saves the current in-memory dataset state to a temporary file and pushes it onto a stack.
  • A default restore pops 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 restore in your ADO, the stack will retain that extra state. You’ll need an additional restore in the interactive session to get back to your initial preserved state.
  • Use restore, not to skip restoring the most recent state (if you want to keep it), or restore, all to clear the entire stack and revert to the first preserved state.

内容的提问来源于stack exchange,提问作者FalafelPita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:12:33