title: Using Rollapply on two columns
body: <p>I'm trying to do something similar I was asking for <a href="https://stackoverflow.com/questions/4472691/calculate-returns-over-period-of-time">here</a> and unfortunately I cannot work it out.</p>
  
  <p>This is my data frame (data), a time series of prices:</p>
  
  <pre><code>Date          Price   Vol
  1998-01-01     200      0.3
  1998-01-02     400      0.4
  1998-01-03     600     -0.2
  1998-01-04     100      0.1
  ...
  1998-01-20     100      0.1
  1998-01-21     200     -0.4
  1998-01-21     500      0.06
  ....
  1998-02-01     100      0.2
  1998-02-02     200      0.4
  1998-02-03     500      0.3
  1998-02-04     100      0.1
  etc.
  </code></pre>
  
  <p>I would like to tell R, to </p>
  
  <ul>
  <li>take the 1st value of "Vol" and divide it by the 20th value of "Price", then</li>
  <li>take the 2st value of "Vol" and divide it by the 21th value of "Price", then.</li>
  <li>take the 3st value of "Vol" and divide it by the 22th value of "Price", then</li>
  <li>etc.</li>
  </ul>
  
  <p>In my other post, I was able to use this function to calculate a return over a holding period of 20 days:</p>
  
  <pre><code>&gt; data.xts &lt;- xts(data[, -1], data[, 1])
  &gt; hold &lt;- 20
  &gt; f &lt;- function(x) log(tail(x, 1)) - log(head(x, 1))
  &gt; data.xts$returns.xts &lt;- rollapply(data.xts$Price, FUN=f, 
    width=hold+1, align="left", na.pad=T)
  </code></pre>
  
  <p>Is there a way to do something very similar for the problem stated above? So something like</p>
  
  <pre><code>f1 &lt;- function(x,y) head(x, 1) / tail(y,1)
  </code></pre>
  
  <p>where x is "Vol" and y is "Price" and then apply "rollapply"?</p>
  
  <p>Thank you very much</p>
  
  <p>UPDATE: @ Dr G:
  Thanks for your suggestions. With a slight change, it did what I wanted!</p>
  
  <pre><code>data.xts &lt;- xts(data[, -1], data[, 1])
  hold &lt;- 20
  data.xts$quo &lt;- lag(data.xts[,2], hold) / data.xts[,1]
  </code></pre>
  
  <p>Now my problem is, that the resulting data frame looks like this:</p>
  
  <pre><code>    Date          Price   Vol     quo
  1 1998-01-01     200      0.3     NA
  2 1998-01-02     400      0.4     NA
  3 1998-01-03     600     -0.2     NA
  4 1998-01-04     100      0.1     NA
  ...
  21 1998-01-20    180      0.2     0.003 
  </code></pre>
  
  <p>I know that there must be NA's as an outcome, but only for the last 20 observations, not the first 20 ones. The formula stated above calculates the correct values, however puts them starting at the 21st row instead of the first row. Do you know how I could change that? </p>