我需要对20个句点进行以下计算,并且与forval
命令不相符,因为我正在学习如何处理Stata。
这是我需要重复20个时期的内容:
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
并尝试使用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'
}
答案 0 :(得分:2)
研究egen
的帮助,看它比你想象的更灵活。
egen avg1 = mean(price1), by(Period)
egen avg2 = mean(price2), by(Period)
gen AVG_t1 = (avg1 + avg2) / 2
您的循环将失败,因为第二次avg1
已经存在。记录的内容是
bysort Period: egen avg1 = mean(price1)
by Period: egen avg2 = mean(price2)
但上面的语法可行。