title: R: write a loop code to go through every nth rows and do a function in datatable?
body: <p>I wonder how to write a <code>loop code</code> to go through every <code>nth</code> rows and do a <code>function</code>. </p>
  
  <p>for example,<br></p>
  
  <p>1-  I'd like to <code>sort</code> descending every two lines <code>(#1 &amp; #2)</code>, <code>(3&amp;#4)</code> and <em>etc</em>.<br>
  2-  I'd like to calculate the <code>mean</code> of var1 for every two lines <code>(#1 &amp; #2)</code>, <code>(#3&amp;#4</code>) and <em>etc</em>.</p>
  
  <p>For example, I'd like to order <code>every two rows</code> in <code>df</code> based on <code>ID</code> column :</p>
  
  <pre><code>    library(data.table)
      ID &lt;- c("229-220", "229-27", "229-321", "229-36")
      Var1 &lt;- LETTERS[1:4]
      Var2 &lt;- rnorm(4,4,1)
      df&lt;- data.frame(ID, Var1, Var2)
      setDT(df)
      df
             ID Var1     Var2
  1: 229-220    A 4.497850
  2:  229-27    B 2.033383
  3: 229-321    C 4.701356
  4:  229-36    D 3.527209
  </code></pre>
  
  <p>Expected results:</p>
  
  <pre><code>### for the first question I'd like to get something similar to this:
           ID    Var1    Var2
      1  229-27    B     2.033383 
      2  229-220   A     4.497850
      3  229-36    D     3.527209
      4  229-321   C     4.701356
  
   ### for the second question I'd like to get something similar to this:
            com              mean
            A-B             4.49785
            C-D             3.527209
  </code></pre>
  
  <p>I tried different things but was useless. </p>
  
  <p><strong>Please Provide an answer or hint for me to get help rather than just simply downvote it!</strong></p>