Saving and using temporary files on disk
In previous examples we often created a file on disk that we needed only for the duration of the example. We erased the file at the end of the example to clean up after ourselves.
Stata supplies the tempfile command to get around creating and erasing permanent files. However, temporary files are a bit tricky to work with, and I don't recommend using them in everyday work. They're best suited to programs, that is sets of Stata commands that are executed together. Most researchers work with a few commands at a time in a do-file, which makes temporary files cumbersome. For completeness, however, here is an example of the tempfile command:
clear use "t:\statatut\exampw1.dta" sort v001 v002 v003 tempfile temp1 /* create a temporary file */ save "`temp1'" /* save memory into the temporary file */ use "t:\statatut\exampw2.dta" sort v001 v002 v003 merge v001 v002 v003 using "`temp1'" /* use the temporary file */
1. The name temp1 in the save and merge commands is enclosed in single quotes. Why is that? Answer.
2. Why don't we need to erase temp1 after we're finished with it? Answer.
1. The name "temp1" is actually a temporary variable name, which is called a "macro" in Stata. In this case it refers to a temporary file. Looking in the log you'll see that the actual temporary file is named something like:
The macro "temp1" contains that value. To get that value, we need to put the accent mark (`) in front of the macro name and a single quote after the macro name.
Note that you must use the "backward" single quote (accent mark on the tilda key) at the beginning of your macro name, and the "forward" single quote (apostrophe on the double-quotes key) at the end of your macro name when you refer to the file.
2. We don't need to erase temp1 because Stata takes care of that for us.