title: Order on a list
body: <p>I've encountered an application where I need to sort a data.frame by column numbers, and none of the <a href="https://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-columns-in-r/6871968#6871968">usual solutions</a> seem to allow that.</p>
  
  <p>The context is creating an <code>as.data.frame.by</code> method.  Since a <code>by</code> object will have its last column as the value column and the first ncol-1 columns as the index columns.  <code>melt</code> returns it sorted backwards--index 3, then index 2, then index 1.  For compatibility with <code>latex.table.by</code> I'd like to sort it forwards.  But I'm having trouble doing that in a sufficiently generic way.  The commented-out line in the function below is my best attempt so far.</p>
  
  <pre><code>as.data.frame.by &lt;- function( x, colnames=paste("IDX",seq(length(dim(x))),sep="" ), ... ) {
    num.by.vars &lt;- length(dim(x))
      res &lt;- melt(unclass(x))
    res &lt;- na.omit(res)
      colnames(res)[seq(num.by.vars)] &lt;- colnames
      #res &lt;- res[ order(res[ , seq(num.by.vars)] ) , ] # Sort the results by the by vars in the heirarchy given
      res
  }
  
  dat &lt;- transform( ChickWeight, Time=cut(Time,3), Chick=cut(as.numeric(Chick),3) )
  my.by &lt;- by( dat, with(dat,list(Time,Chick,Diet)), function(x) sum(x$weight) )
  &gt; as.data.frame(my.by)
              IDX1         IDX2 IDX3 value
  1  (-0.021,6.99] (0.951,17.3]    1  3475
  2      (6.99,14] (0.951,17.3]    1  5969
  3        (14,21] (0.951,17.3]    1  8002
  4  (-0.021,6.99]  (17.3,33.7]    1   640
  5      (6.99,14]  (17.3,33.7]    1  1596
  6        (14,21]  (17.3,33.7]    1  2900
  13 (-0.021,6.99]  (17.3,33.7]    2  2253
  14     (6.99,14]  (17.3,33.7]    2  4734
  15       (14,21]  (17.3,33.7]    2  7727
  22 (-0.021,6.99]  (17.3,33.7]    3   666
  23     (6.99,14]  (17.3,33.7]    3  1391
  24       (14,21]  (17.3,33.7]    3  2109
  25 (-0.021,6.99]    (33.7,50]    3  1647
  26     (6.99,14]    (33.7,50]    3  3853
  27       (14,21]    (33.7,50]    3  7488
  34 (-0.021,6.99]    (33.7,50]    4  2412
  35     (6.99,14]    (33.7,50]    4  5448
  36       (14,21]    (33.7,50]    4  8101
  </code></pre>
  
  <p>With the line uncommented, it returns gibberish (it just treats the whole data.frame as a vector, with disastrous results).</p>
  
  <p>I've even tried clever stuff like <code>res &lt;- res[ order( ...=list(res[,1],res[,2]) ) , ]</code> but to no avail.</p>
  
  <p>I suspect there's a simple way to do this, but I'm not seeing it.</p>
  
  <p><strong>Edit for clarification</strong>: I want to not have to specify column names. Instead, I want to be able to sort it by a numerical vector (e.g. sort by columns 1:4). </p>