title: How to calculate rolling correlation between rows in an xts?
body: <p>I have an xts of yearly data. I am trying to get the rank correlation between each year. For example, this is a subset of my xts:</p>
  
  <pre><code>&gt; yearlyRanks[16:20,45:55]
             35881 35880 42261 33445 46087 31486 8981 7687 8203 8202 41383
  2009-12-31     8     9    19     8    18    18   16    4   16   16    20
  2010-12-31     4     3    20     6    19     2   17   17   17   17    21
  2011-12-31     3     4    21     3    20     1   18   18   18   18    22
  2012-12-31     6     6    22     5    21    19   19   19   19   19     4
  2013-12-31     7     7     3     4    22    20   20   20   20   20     2
  </code></pre>
  
  <p>I would like to know the correlation between the ranks in each year with the preceding year. (Trying to tell how well this year's rank was predicted by last year's.)</p>
  
  <p>I am trying to use this:</p>
  
  <pre><code>yearlyCors &lt;- rollapplyr(coredata(yearlyRanks), width = 2, function(x) cor(x[1], x[2], use = 'n'))
  </code></pre>
  
  <p>But it takes FOREVER, and it doesn't seem to work. I think it is because I am passing it a set of 2 rows, so it wants to return 2 values, but I am only expecting 1. (Does that make sense?)</p>
  
  <p>Any ideas on how I would do this?</p>
  
  <p>EDIT:</p>
  
  <p>Just to be clear, this is what i would want from that subset:</p>
  
  <pre><code>&gt; test &lt;- yearlyRanks[16:20,45:55]
  &gt; c(cor(test[1,], test[2,]), cor(test[2,], test[3,]), cor(test[3,], test[4,]), cor(test[4,], test[5,]))
  [1] 0.4679246 0.9930253 0.4854528 0.7193598
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>What I want is the diag() + 1 of the correlation matrix. Here is the correlation matrix (of the transpose):</p>
  
  <pre><code>&gt; cor(t(test))
             2009-12-31 2010-12-31 2011-12-31 2012-12-31 2013-12-31
  2009-12-31 1.00000000  *0.4679246*  0.4716995  0.3722922 0.08786426
  2010-12-31 0.46792463  1.0000000  *0.9930253*  0.4654688 0.17192856
  2011-12-31 0.47169948  0.9930253  1.0000000  *0.4854528* 0.20237689
  2012-12-31 0.37229225  0.4654688  0.4854528  1.0000000 *0.71935975*
  2013-12-31 0.08786426  0.1719286  0.2023769  0.7193598 1.00000000
  </code></pre>
  
  <p>You can see the starred values are the ones I want. Is there a way to access the diag + 1 (if you follow)?</p>