title: R apply and get values from previous row
body: <p>I'd like to use the previous row value for a calculation involving the current row. The matrix looks something like:</p>
  
  <pre><code>      A   B
  [1,]  1   2
  [2,]  2   3
  [3,]  3   4 
  [4,]  4   5
  [5,]  5   6
  </code></pre>
  
  <p>I want to do the following operation: <code>(cell[i]/cell[i-1])-1</code>, essentially calculating the % change (-1 to 1) from the current row to the previous (excluding the first row).</p>
  
  <p>The output should look like:</p>
  
  <pre><code>         C      D
  [1,]    NA     NA
  [2,]   1.0    0.5
  [3,]   0.5   0.33 
  [4,]  0.33   0.25
  [5,]  0.25   0.20
  </code></pre>
  
  <p>This can be accomplished easily using for-loops, but I am working with large data sets so I would like to use apply (or other inbuilt functions) for performance and cleaner code.</p>
  
  <p>So far I've come up with:</p>
  
  <pre><code>test.perc &lt;- sapply(test, function(x,y) x-x[y])
  </code></pre>
  
  <p>But it's not working.</p>
  
  <p>Any ideas?</p>
  
  <p>Thanks.</p>