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

Re: st: tempvar


From   wgould@stata.com (William Gould)
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: tempvar
Date   Fri, 07 Jun 2002 11:27:04 -0500

Anna-Lisa Pierre <annaf2001@hotmail.com> wrote, 

> I am trying to use the 'tempvar' command so that I do not have to drop
> variables at the end. However, I am having problems using this within loops.
> Are 'tempvar' and 'tempname' not supposed to be used within loops?

There is no problem using -tempvar- and -tempname- in loops, but the commands
may not do what you what you anticipate.  Inside a loop or outside, the
variables will be dropped when then the program ends, not when the loop ends.

For instance, the following will work, but use more memory than necessary:

        while (...) {
                tempvar this
                gen `this' = ...
                replace that = ... `this' ...
        }

The above fragment will create many temporary variables.  All will get
destroyed eventually (when the program ends), but until then, they will 
tie up memory.  Better would be to code, 

        tempvar this
        while (...) {
                gen `this' = ...
                replace that = ... `this' ...
                drop `this'
        }

This is not to say that -tempvar- within loops is always to be avoided, but it
should be avoided unless you are going to the trouble of saving the temporary
name somewhere because you later need to refer to it.  E.g., I have coded,

        local tvars = "" 
        while (...) {
                tempvar next 
                gen `next' = ...
                local tvars `tvars' `next'
        }

and then, later in the code, coded

        foreach var of local tvars {
                ...
        }

-- Bill
wgould@stata.com

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



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