【问题标题】:Stata egen combined with ifStata egen 与 if 结合
【发布时间】:2014-05-04 17:49:26
【问题描述】:

我有这样的数据

year month X    Y    weight  
2013    1   1    0    1000
2001    12  0     1    2000

我想基于XY 变量创建一个变量Z,以year 为条件。我在 2002 年之前和之后有两个 year 公式。如果我使用 egenif

if year > 2002 {
   bysort year month  :egen Z= total( x*weight)
}
else {
bysort year month : egen Z= total(y*weight*0.5)
}

此代码不起作用,因为如果 year <2002 ,Stata 会报告 z 已经创建。有什么方法可以实现目标吗?

我使用了一种非常粗暴蛮力的方法来解决这个问题。我为 z 创建了两个变量,即 z 和 z_2002。然后如果年份小于 2002,我将 z 替换为 z_2002。

【问题讨论】:

  • “已创建”错误不是您唯一的问题。您错误地使用了编程 ifcmd 而不是 if 限定符(help if)。请参阅stata.com/support/faqs/programming/… 只有符合条件的 if 可用于对观察子集进行操作。
  • 让我们重新开始。你到底想要什么?是否如下: 1. 有两条规则,一条用于 2002 年之前,一条用于 2002 年之后。 2. Z 是 x 或 y 与年份相关的每月函数的年总和。这是正确的吗?
  • z 是每个月和每个年的月总和。 z 的公式因年份而异。
  • @YanSong 看来您已经通过编辑原始问题回答了自己的问题。很高兴您回答了自己的问题。我不确定这是否仍然算作一个问题。
  • @fsmart 正如我在问题中所说,我的方法不够优雅。我希望有人会有更好的方法

标签: stata


【解决方案1】:

如果我理解正确,这应该可以。

第一步计算乘积(以年份为条件),第二步计算总和。

正如其他答案已经指出的那样,if 限定符和if 编程命令之间存在差异。对此有一个简短的常见问题解答:http://www.stata.com/support/faqs/programming/if-command-versus-if-qualifier/

(我在对另一个答案的评论中使用@NickCox 提供的代码。)

clear all
set more off

*----- example data -----

input year month x    y    weight
2013    1   1    0    1000
2013    1   1    0    800
2013    2   0    1    1200
2013    2   1    0    1400
2001    12  1     0    1500
2001    12  0     1    2000
2001    11  1     1    4000
end

sort year month
list, sepby(year month)

*----- computations -----

gen Z = cond(year > 2002, x * weight, y * weight * 0.5)
bysort year month: egen totZ = total(Z) // already sorted so -by- should be enough

list, sepby(year month)

【讨论】:

  • 您可以将cond() 调用放在total() 中,因为total() 以表达式为基础,并且不坚持其参数是变量名。
  • 谢谢@Nick。没错,当然。虽然有时我宁愿多写一两行来增加可读性。在这种情况下,我只是想强调解决方案的两步顺序。
  • 很好的答案,罗伯托。
【解决方案2】:
clear
input year month x    y    weight
2013    1   1    0    1000
2001    12  0     1    2000
end

preserve
keep if year>2002
bysort year month  :egen z= total(x*weight)
tempfile t1
save `t1'
restore
keep if year<=2002
bysort year month : egen z= total(y*weight*0.5)
append using `t1'
list

【讨论】:

  • 你的方法行得通。到目前为止,我所做的是创建两个不同的变量 z 和 z_2002。如果年份在 2002 年之前,我将 z 替换为 z_2002。
猜你喜欢
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多