在Stata中采取条件均值

时间:2009-10-10 04:47:59

标签: statistics stata

假设我有一个包含两个变量的Stata数据集:typeprice。每个观察值的type值是1到10之间的数字。

我想添加第三个值,即price的所有变量的平均值type。因此,例如,如果第一个观察的type为3,price为10,那么我想添加第三个值,即所有观察值的平均值price type = 3。

我怎样才能在Stata中做到这一点?

3 个答案:

答案 0 :(得分:6)

这是一种更简单有效的不同方法。如果你有一个大数据集,这将比aTron建议的多步循环更快,这种方法适应你的“类型”变量范围的变化(如果你的数据集大小改变,你不必返回代码并更改forvalues命令中的范围。

1)创建假数据集

clear
input type price
1 1000
2 3200
3 5000
4 1200
5 1000
1 4000
2 2000
3 4000
4 1200
5 2000
end

2)按price

生成平均type
bysort type: egen meanprice = mean(price)

li type price meanprice, sepby(type) 

答案 1 :(得分:1)

可能有几种方法可以做到这一点,但这就是我的建议。

gen newvar = .
forvalues i = 1/10 {

  qui sum price if type == `i', meanonly
  replace newvar = r(mean) if type == `i'

}

答案 2 :(得分:1)

您可以使用

创建方法
by type: egen conditional_mean = mean(price)