Preserve and restore commands in Stata

May 01, 2019

Let’s say you want to make some temporary in-memory manipulations of your data without having to reload the whole dataset in order to get back. This can be achieved by use of the preserve and restore commands. In this example we’ll drop all observations with a wage lower than $40.

sysuse nlsw88, clear  
drop if wage < 40  

Result of dropping observations

Ouch, that’s the majority of observations dropped right there. The only way to get them back at this point we need to reload the entire dataset. However, if before dropping we insert the preserve command, then we’ll be able to restore the data afterwards:

preserve
drop if wage < 40  
restore
su

As we can see in the result, all of the dropped observations have now been restored.

Result of restoring observations


Profile picture

Written by Johan Osterberg who lives and works in Gothenburg, Sweden as a developer specialized in e-commerce. Connect with me on Linkedin

2024 © Johan Osterberg