【问题标题】:Stata moving averages based on time window, not # observations基于时间窗口的统计移动平均值,而不是 # 个观察值
【发布时间】:2013-12-07 20:40:55
【问题描述】:

我有一份人员、注册时间和分数的列表。在 Stata 中,我想根据每个观察值周围的时间窗口(而不是基于滞后/领先观察值的窗口)计算得分的移动平均值。

例如,假设两边各有 +/- 2 天且不包括当前观察,我试图计算如下:

user_id   day     score  window_avg
A         1        1     1.5             = (avg of B and C)
B         1        2     1               = (avg of A and C)
C         3        1     2.25            = (avg of A, B, D, and E)
D         4        3     2               = (avg of C and E)
E         5        3     2.5             = (avg of C, D, F, and G
F         7        1     4               = (avg of E and G)
G         7        5     2               = (avg of E and F)
H         10       3     .               = blank

我尝试使用tsset 定义数据集,然后使用tssmooth,但无法正常工作。由于在给定的时间段内可能有多个观察结果,我不确定这是否是正确的方法。此外,实际上 day 变量是 tc 时间戳。

【问题讨论】:

    标签: stata moving-average


    【解决方案1】:

    tsset 在这里也无济于事,即使您有规律地间隔时间,因为您有一些重复的时间值,但您的数据不符合 Stata 意义上的面板数据。但是问题应该让位于可能性的循环。首先,让我们从字面上使用整数天来举个例子。

    gen window_avg = . 
    su day, meanonly 
    
    qui forval d = `r(min)'/`r(max)' { 
        su score if inrange(day, `d' - 2, `d' + 2), meanonly 
        replace window_avg = (r(sum) - score) / (r(N) - 1) if day == `d'
    }  
    

    这里我们假设没有缺失值。发扬光大的原则是

    其他人的平均值 =(所有的总和 - 此值)/(值的数量 - 1)

    http://www.stata.com/support/faqs/data-management/creating-variables-recording-properties/讨论

    实际上,您不希望以毫秒为单位循环遍历所有可能的日期时间。因此,请尝试对这种形式的观察进行循环。注意<pseudocode> 元素。

    gen window_avg = . 
    
    qui forval i = 1/`=_N' { 
        su score if inrange(date, <date[`i'] - 2 days>, <date[`i'] + 2 days>), meanonly 
        replace window_avg = (r(sum) - score) / (r(N) - 1) in `i' 
    }  
    

    这篇论文也是相关的:

    Cox, N.J. 2007。间隔事件。 Stata 期刊 7:440-443。 http://www.stata-journal.com/sjpdf.html?articlenum=pr0033

    如果可能有遗漏,则需要更复杂的一行:

        replace window_avg = (r(sum) - cond(missing(score), 0, score)) / (r(N) - !missing(score)) in `i' 
    

    意味着如果当前值缺失,我们从总和中减去 0,从观察计数中减去 0。

    编辑:以毫秒为单位的 2 天,利用内置函数并使用 cofd(2)

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2016-05-01
      • 2021-04-11
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      相关资源
      最近更新 更多