Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Question on loop over variable


From   Phil Clayton <[email protected]>
To   [email protected]
Subject   Re: st: Question on loop over variable
Date   Fri, 29 Jul 2011 16:06:48 +1000

You've declared `data' to be a temporary file, but haven't saved anything to it. So then when you try to open it, the file is missing - hence the error.

Rather than loading the file each time, it might be quicker to use -preserve- and -restore- (I also tweaked the last -bys- line):

==========begin code=========
use data, clear

levelsof itemid, local(levels)

foreach l of local levels{
preserve
keep if itemid == "`l'"
bys monthly: replace total_purchase_price = sum(extendedcost)
bys monthly: replace total_quantity = sum(itemqty)
replace average_purchase_price = total_purchase_price / total_quantity

bys monthly: keep if _n==1
outsheet using "C:\Documents and Settings\MPTMP026\Desktop\new\`l'.txt"
restore
}
===========end code==========

Phil

On 29/07/2011, at 11:12 AM, Guo Chen wrote:

> Hi, all:
> 
> I wanna calculate monthly average purchase price for all the products
> in my data set, so I need loop over all values of variable "itemid".
> 
> I checked http://www.stata.com/support/faqs/data/foreach.html  and the
> following code is the best I can do, but I still got error messege:
> 
> 
> file C:\DOCUME~1\MPTMP026\LOCALS~1\Temp\ST_0000000t.tmp not found
> r(601);
> 
> Can you please take a look at my code?
> 
> ==========begin code=========
> use data, replace
> 
> tempfile data
> 
> levelsof itemid, local(levels)
> 
> foreach l of local levels{
> use "`data'", clear
> keep if itemid == "`l'"
> bys monthly: replace total_purchase_price = sum(extendedcost)
> bys monthly: replace total_quantity = sum(itemqty)
> replace average_purchase_price = total_purchase_price / total_quantity
> 
> bys monthly: gen i = [_n]== 1
> drop if i != 1
> outsheet using "C:\Documents and Settings\MPTMP026\Desktop\new\`l'.txt"
> }
> 
> 
> 
> --
> Guo Chen
> University of Minnesota
> Dept. of Applied Economics
> 125-E Ruttan Hall
> 1994 Buford Avenue
> St. Paul, MN 55108
> 612-423-7031
> *
> *   For searches and help try:
> *   http://www.stata.com/help.cgi?search
> *   http://www.stata.com/support/statalist/faq
> *   http://www.ats.ucla.edu/stat/stata/


*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index