Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: preserve & restore

Subject   st: RE: preserve & restore
Date   Sun, 23 Feb 2003 09:54:28 -0500

Jun Xu (
> Question about multiple perserve and restore in an ado file.  
> Here Stata 
> will produce error message since I have two preserve's in the 
> following ado 
> file.  As I need to create a data set that is a subset of the 
> one managed 
> within the second "preserve", I use preserve and restore 
> since I am going to 
> work on the one immediately before the second preserve.  But 
> I still need to 
> put preserve right below program define command since there 
> are some other 
> manipulations outside the second preserve/restore block like the sort 
> command.  One way that's possible is to undo some data 
> management witin this 
> ado like sort back to the original data before executing this 
> ado file as I 
> am doing at teh end of the ado file.  But are there any other 
> tricks to go 
> about it?
> ****************************************************
> for num 1/6: set obs 100\ gen xX=invnorm(uniform())
> capture program drop trial
> 	program define trial
> 	perserve   /*first perserve*/
> 	tempvar obsn what
>         quietly gen `obsn'=_n
>         ***Do other stuff that changes the original data look
>         sort x4 /*such as sort by x4*/
> 	preserve  /*second preserve*/
>         gen `what'=101-_n
> 	sort `what'
>         ***
>         ***do other stuff here based on the sorted order
>         ***such as just keep the top 10 values of `what'
> 	drop if x3==.
> 	save h:\trial2.dta, replace
> 	restore /*second restore*/
>         *do something else here that might change the order
>         *or look of the original data
>          sort `obsn'
>    restore /*corresponding to the first preserve, though not 
> necessary*/
> end
> trial

You can't preserve data twice unless you issue a -restore- or a -restore,
not- (to cancel the initial preserve) in between.

You can accomplish what I think you are trying to do by saving your data in
temporary files rather than preserving it

	tempfile file1 file2
	* replace your 1st preserve by
	save "`file1'"
	* ... and the second preserve by
	save "`file2'"

Then you'll have complete freedom over which particular file you want to
load back into memory by using -use- rather than -restore-.  The
double-quotes around the temporary filenames ensure the files will be saved
properly if the path to your temporary directory contains an embedded space.
(Also use the double-quotes when you later load the data, i.e. -use
"`file1'", clear-.)

Patrick Joly
*   For searches and help try:

© Copyright 1996–2019 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index