title: Calculate moving recency-weighted mean in R
body: <p>I would like to calculate the moving recency-weighted mean finishing positions of a horse given the times (day) and finishing positions (pos) for a sequence of races in which the horse participated.  Such statistics are useful in <a href="http://en.wikipedia.org/wiki/Handicapping" rel="nofollow">handicapping</a>.</p>
  
  <p>Currently, I am using a "loop-inside-a-loop" approach.  Is there a faster or more elegant R-language approach to this problem?</p>
  
  <pre><code>#
  # Test data
  #
  
  day &lt;- c(0, 6, 10, 17, 21, 26, 29, 31, 34, 38, 41, 47, 48, 51, 61)
  pos &lt;- c(3, 5, 6, 1, 1, 3, 4, 1, 2, 2, 2, 6, 4, 5, 6)
  testdata &lt;- data.frame(id = 1, day = day, pos = pos, wt.pos = NA)
  
  #
  # No weight is given to observations earlier than cutoff
  #
  
  cutoff &lt;- 30
  
  #
  # Rolling recency-weighted mean (wt.pos)
  #
  
  for(i in 2:nrow(testdata)) {
    wt &lt;- numeric(i-1)
    for(j in 1:(i-1))
      wt[j] &lt;- max(0, cutoff - day[i] + day[j] + 1)
      if (sum(wt) &gt; 0)
        testdata$wt.pos[i] &lt;- sum(pos[1:j] * wt) / sum(wt)
  }
  
  &gt; testdata
  
     id day pos   wt.pos
  1   1   0   3       NA
  2   1   6   5 3.000000
  3   1  10   6 4.125000
  4   1  17   1 4.931034
  5   1  21   1 3.520548
  6   1  26   3 2.632911
  7   1  29   4 2.652174
  8   1  31   1 2.954128
  9   1  34   2 2.436975
  10  1  38   2 2.226891
  11  1  41   2 2.119048
  12  1  47   6 2.137615
  13  1  48   4 3.030534
  14  1  51   5 3.303704
  15  1  61   6 4.075000
  </code></pre>