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
Andrew Dyck <[email protected]>
To
[email protected]
Subject
Re: st: Question on loop over variable
Date
Thu, 28 Jul 2011 23:08:16 -0700
I'm going to suggest trying to avoid the foreach loop using -bysort-.
It looks like you are already using it for the variable _monthly_ to
create a price per itemid for every month (presumably your data is
daily or weekly?). I would suggest considering the following:
1. collapse your data to be monthly
collapse (sum) extendedcost itemqty, by(monthly)
2. generate a price variable
gen purchase price = extendedcost / itemqty
3. generate an average price by itemid
bysort itemid : egen average_purchase_price = mean(price)
Maybe I've misunderstood your aims but hopefully that is of some help
Cheers,
Andrew
On Thu, Jul 28, 2011 at 6:12 PM, Guo Chen <[email protected]> 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/