将 egen 函数与 replace 结合使用
Using egen functions with replace
我使用 egen
:
从另一个变量的平均值创建了一个新变量
egen afd_lr2 = mean(afd_lire2w) if ost == 0
现在我想用另一个变量的平均值替换这些值 if 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)
更容易理解,程序员应该会想到。
我使用 egen
:
egen afd_lr2 = mean(afd_lire2w) if ost == 0
现在我想用另一个变量的平均值替换这些值 if 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)
更容易理解,程序员应该会想到。