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

Re: st: tempfile & scope


From   Nicholas Winter <[email protected]>
To   [email protected]
Subject   Re: st: tempfile & scope
Date   Thu, 25 Sep 2003 12:09:36 -0400

At 07:14 PM 9/24/2003 -0400, you wrote:
Hi,

Suppose I want to create 2 temporary datasets inside a -forval- loop, with
names indexed by the loop number (i.e., `results0', `results1'). Once I get
outside the loop, I want to append them using -dsconcat-, but since I
defined them inside the loop, they no longer exist.

A more concrete example:

forval k = 0(1)1 {

    tempname memhold
    tempfile results

    postfile `memhold' var1 var2 var3 using `results'`k', replace

    forval y = 1998(1)2002 {
        ...

        post `memhold' (`x') (`y') (`z')
    }

    postclose `memhold'
}

dsconcat `results0' `results1'

Could someone offer a suggestion on how to do this, please? Much thanks.
I think this isn't a scope problem, but a local macro naming issue. I think you need to modify the way you get and use the -tempfiles-.

Currently in the loop you do:

tempfile results

then you post to a file called `results'`k' , which will be the name of the -tempfile- Stata gave you, with the number 0 or 1 appended. That might or might not even be a legal filename on your OS. Then outside your loop, you refer to the locals `results0' and `results1' -- you never defined those locals.

Instead, your tempfile command should read:

tempfile results`k'

On the first iteration, this will create a local macro called `results0'; on the second iteration it will create `results1'.

So inside the loop, post to `results`k''

Then at the end, after the loop, you can refer to `results0' and `results1'.

By the way, I'm not clear why you need the -tempname- for the posting defined repeatedly; you could just define one outside the loop, and reuse it repeatedly.


--Nick Winter







*
* 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–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index