【问题标题】:Stata: Replacing egen in a loopStata:循环替换egen
【发布时间】:2014-10-30 14:31:34
【问题描述】:

我正在尝试根据不同的if 条件计算非缺失值。然后每个月使用max

gen xx1=.
gen xx2=.

forvalues i = 1/12{
bys state year month: replace xx1= 1 if month==`i' & no_monthsreport>=`i'
bys state year month: replace xx2= sum(!missing(xx1))
bys state year month: egen tot_xx3 =max(xx2)
}

我注意到egen 命令不能是replaced。所以循环不起作用。我想知道是否有一种方法可以在不创建更多变量的情况下做到这一点。

【问题讨论】:

    标签: stata


    【解决方案1】:

    直接的答案是egen没有replace选项,也没有replace-type命令对应egen。因此,您需要 droprename 任何先前的结果,其变量名称与您要在 egen 命令中使用的变量名称相同。

    然而,在这个问题中,egen 不需要任何方式,并且循环看起来也放置错误。我不明白你想做什么,但我认为你想要更像

    gen xx1 = .
    forvalues i = 1/12 {
        replace xx1 = 1 if month == `i' & no_monthsreport >= `i'
    } 
    bys state year month: gen xx2 = sum(xx1)
    bys state year month: gen tot_xx3 = xx2[_N] 
    

    注意

    1. xx1 的计算不需要 by: 的框架,因为没有任何东西依赖于周围的观察组。

    2. xx1 的运行或累计和的计算可以只进行一次。

    3. 通过构造,xx1 要么缺失要么为 1。因此,xx1 在不为 1 时不会准确缺失。无需启动 missing() 函数,然后在可以时将其取反直接数1。

    4. 1s 的运行和的最大值就是最后一个值。 (sum() 会忽略缺失。)

    您是否希望stateyear month 分别进行计算取决于您,但这种选择通常会导致错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 2019-11-04
      • 1970-01-01
      相关资源
      最近更新 更多