title: What is the most effective way to sort dataframe and add special id?
body: <p>I have a very very big dataset and I am looking for the fastest and most effective way to sort and give an id to a dataframe based on values in two columns. I have a dataframe where column <code>"value 1"</code> has unique values while column <code>"value 2"</code> has not. column <code>"absdiff"</code> gives the difference between these two columns. I want to add <code>ID</code> in the dataframe as first column which gives the closest distance to the respective "group/value" in the column <code>"value2"</code>. So, exemplatory this is what I have:</p>
  
  <pre><code>data &lt;- data.frame(value1 = c(5,5.1,5.2,4.9,8.2,8.0,13,13.3,18), 
                     value2 = c(5,5,5,5,8,8,13,13,18))
  data$absdiff &lt;- with(data, c(abs(data$value1 - data$value2)))
  
    value1 value2 absdiff
    5.00      5    0.00
    5.10      5    0.10
    5.20      5    0.20
    4.89      5    0.11
    8.20      8    0.20
    8.00      8    0.00
   13.00     13    0.00
   13.30     13    0.30
   18.00     18    0.00
  </code></pre>
  
  <p>and what I want to have is (note the slight different order as <code>ID</code> is sorted):</p>
  
  <pre><code>ID  value1 value2 absdiff
  1   5.00      5    0.00
  2   5.10      5    0.10
  3   4.89      5    0.11
  4   5.20      5    0.20
  1   8.00      8    0.00
  2   8.20      8    0.20
  1  13.00     13    0.00
  2  13.30     13    0.30
  1  18.00     18    0.00
  </code></pre>
  
  <p>I know there is plyr, apply etc. But what is the most effective way, are there others? The dataset I have is in GB range so it makes a difference. </p>