Jensus
Jensus

Reputation: 11

Stata: calculating averages over time

I need to do the following calculation for 20 periods and did not get along with the forval command, since I'm just learning how to handle Stata.

This is what I need to repeat for 20 periods:

egen avg1 = mean(price1) if  Period == 1
egen avg2 = mean(price2) if  Period == 1
gen AVG = avg1+avg2
gen AVG_t1=AVG/2
drop avg1 avg2 AVG

and tried to solve it using forval:

    sort Period
local j = Period
forval j = 1/20 { 
     egen avg1 = mean(price1) if  Period == `j' 
     egen avg2 = mean(price2) if  Period == `j'
     gen AVG = avg1+avg2 if  Period == `j' 
     gen AVG_t`j'=AVG/2 if  Period == `j'  
     drop avg1 avg2 AVG if Period == `j' 
} 

Upvotes: 1

Views: 227

Answers (1)

Nick Cox
Nick Cox

Reputation: 37208

Study the help for egen to see that it is more flexible than you think.

 egen avg1 = mean(price1), by(Period) 
 egen avg2 = mean(price2), by(Period) 
 gen AVG_t1 = (avg1 + avg2) / 2 

Your loop will fail because second time around avg1 already exists. What is documented is

 bysort Period: egen avg1 = mean(price1) 
 by Period: egen avg2 = mean(price2) 

but the syntax above will work.

Upvotes: 2

Related Questions