Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • recursive weighted mean

    Dear All, I find this question here (in Chinese). Suppose the data set is
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str8 halfyear float variable
    "2004h2"  .1158473
    "2005h1"   .197123
    "2005h2"  .6549371
    "2006h1"  .7112523
    "2006h2" -.8110056
    "2007h1" -.1182826
    "2007h2" -.0018191
    "2008h1" -.2019278
    "2008h2"  .0102702
    "2009h1" -.2379171
    "2009h2" -.0918824
    "2010h1" -.0150432
    "2010h2"  .9090409
    "2011h1"  -.047904
    "2011h2"  .0365674
    "2012h1"  .3524516
    "2012h2"  .0381953
    "2013h1"  .0701639
    "2013h2"   .030052
    "2014h2" -.1281992
    end
    Suppose this is a time series (panel data should follow the same method). For the first wanted value, it is the first value of variable times weight 1, i.e., itself. For the second wanted value, it is weighted sum of the second value of variable ( .197123) times 1+the first value of variable (1158473) times 1/2. For the third wanted value, it is weighted sum of the third value of variable ( .6549371) times 1+second value of variable ( .197123) times 1/2+the first value of variable (1158473) times 1/3, and so on. Any suggestions are highly appreciated.
    Ho-Chuan (River) Huang
    Stata 19.0, MP(4)

  • #2
    I can offer you a slow and naive approach as a first solution. I kept the vars in there so it is easier to see what happens, you will probably drop them or change them to tempvars.


    Code:
    gen id = _n
    gen wanted = variable in 1
    forvalues i = 1 / 20 {
        gen t`i' = variable / (`i' - id + 2)
        gen k`i' = sum(t`i')
        local newline = `i' + 1
        replace wanted = variable + k`i'[_n-1] in `newline'
    }
    Best wishes

    Stata 18.0 MP | ORCID | Google Scholar

    Comment


    • #3
      Another similar solution:

      Code:
      gen w = 1/(_N-_n+1)
      gen wanted = sum(variable*w)
      forvalues i = `=_N-1'(-1)1 {
          replace w = w[_n+1]
          replace wanted = sum(variable*w) in 1/`i'
      }
      drop w

      Comment


      • #4
        Dear @Felix Bittmann and @Fei Wang, Many thanks for the useful suggestions.
        Ho-Chuan (River) Huang
        Stata 19.0, MP(4)

        Comment

        Working...
        X