title: swapping rows and ordering in a data frame
body: <p>I found it a bit tricky to sort some rows in my data frame in R. The data has the following structure.</p>
  
  <pre><code>df &lt;- 
  ID   TIME   DVID    AMT   DV    PERIOD
   1    0      0      50    NA    1 
   1    0.5    1      0     10    1
   1    0.5    2      0     15    1
   2    600    0      100   NA    2
   2    600    1      0     2.5   2
   2    600    2      0     4     2
   2    602    1      0     20    2
   2    602    2      0     35    2
   3    800    0      50    NA    3
   3    800    1      0     5     3
   3    800    2      0     10    3
  </code></pre>
  
  <p>For <code>PERIOD &gt;= 2</code> I want to swap rows for DVID to be DVID 1, 2, then 0 as shown in the output data frame below <code>dfout</code>. The data has to be ordered by ID, TIME, PERIOD as well. </p>
  
  <p>I tried using the <code>orderBy</code> but could reach my goal. An example of using <code>orderBy</code> is this.</p>
  
  <pre><code>library(doBy)
  dfout &lt;- orderBy(~ID+TIME+PERIOD, data=df)
  </code></pre>
  
  <p>The output should be this: </p>
  
  <pre><code>dfout &lt;- 
  ID   TIME   DVID    AMT   DV    PERIOD
   1    0      0      50    NA    1 
   1    0.5    1      0     10    1
   1    0.5    2      0     15    1
   2    600    1      0     2.5   2
   2    600    2      0     4     2
   2    600    0      100   NA    2
   2    602    1      0     20    2
   2    602    2      0     35    2
   3    800    1      0     5     3
   3    800    2      0     10    3
   3    800    0      50    NA    3
  </code></pre>
  
  <p>I would appreciate if somebody share a trick on how to do that in R.</p>