title: How to subtract a row from the row above using a for loop in R?
body: <p>I am trying to learn how to use for loops in R, in particular to subtract a number from it's above number in a column in R.</p>
  
  <p>I know can do this with <code>b &lt;- diff(df$a)</code> or with:</p>
  
  <pre><code>library(dplyr)
  df %&gt;% 
    mutate(b = a - lag(a)) 
  </code></pre>
  
  <p>But I am trying to understand how I can also get the same result with something like:</p>
  
  <pre><code>for(i in 1:nrow(df)){
    result = df[2,] - df[i,]
    print (result)
  }
  </code></pre>
  
  <p>How do I set this for loop so the <code>df[2,]</code> takes every following row, and not just the 2nd row, and subtracts from the row above?</p>
  
  <p>For example I have data like this:</p>
  
  <pre><code>column a
  1
  10
  20 
  </code></pre>
  
  <p>and I want to eventually create a column with the subtractions:</p>
  
  <pre><code>column a    column b
  1             10
  11            9
  20           ...
  
  </code></pre>