使用带有replace的egen函数

使用带有replace的egen函数,replace,stata,mean,Replace,Stata,Mean,我使用egen从另一个变量的平均值创建了一个新变量: egen afd_lr2 = mean(afd_lire2w) if ost == 0 现在,如果ost==1,我想用另一个变量的平均值替换这些值: replace afd_lr2 = mean(afd_lireo) if ost ==1 这是不可能的,因为均值函数不能与replace命令一起使用 我怎样才能实现我的目标?以下几点对我来说很有用: sysuse auto, clear generate price2 = price +

我使用
egen
从另一个变量的平均值创建了一个新变量:

egen afd_lr2 = mean(afd_lire2w) if ost == 0
现在,如果
ost==1
,我想用另一个变量的平均值替换这些值:

replace afd_lr2 = mean(afd_lireo) if ost ==1
这是不可能的,因为均值函数不能与
replace
命令一起使用


我怎样才能实现我的目标?

以下几点对我来说很有用:

sysuse auto, clear

generate price2 = price + 5345

egen a_price = mean(price) if foreign == 0
egen b_price = mean(price2) if foreign == 1

replace a_price = b_price if foreign == 1
这应该行得通

egen afd_lr2 = mean(cond(ost == 0, afd_lire2w, cond(ost == 1, afd_lireo, .))), by(ost) 
下面是一个测试:

clear
input float(group y1 y2)
1 42   .
1 42   .
2  . 999
2  . 999
end

egen mean = mean(cond(group == 1, y1, cond(group == 2, y2, .))), by(group)

tabdisp group, c(mean)

----------------------
    group |       mean
----------+-----------
        1 |         42
        2 |        999
----------------------
关键是
egen
mean()
函数依赖于一个表达式,这个表达式可能比单个变量名更复杂。也就是说,这比我通常建议的要复杂得多

generate work = afd_lire2w if ost == 0
replace work = afd_lireo if ost == 1
egen mean = mean(work), by(ost)
更容易理解,应该以任何方式出现在程序员身上