title: Order and subset a multi-column dataframe in R?
body: <p>I wanted to order by some column, and subset, a multi-column dataframe but the command used did not work</p>
  
  <pre><code>print(df[order(df$x) &amp; df$x &lt; 5,])
  </code></pre>
  
  <p>This does not order the results.</p>
  
  <p>To debug this I generated a test dataframe with 1 column but this 'simplification' had unexpected effects</p>
  
  <pre><code>df &lt;- data.frame(x = sample(1:50))
  
  print(df[order(df$x) &amp; df$x &lt; 5,])
  </code></pre>
  
  <p>This does not order the results so I felt I had reproduced the problem but with simpler data.</p>
  
  <p>Breaking down the process to first ordering and then subsetting led me to discover the ordering in this case does not generate a dataframe object</p>
  
  <pre><code>df &lt;- data.frame(x = sample(1:50))
  ndf &lt;- df[order(df$x),]
  print(class(ndf))
  </code></pre>
  
  <p>produces</p>
  
  <pre><code>[1] "integer"
  </code></pre>
  
  <p>Attempting to subset the resultant "integer" ndf object using dataframe syntax e.g.</p>
  
  <pre><code>print(ndf[ndf$x &lt; 5, ])
  </code></pre>
  
  <p>obviously generates an error:</p>
  
  <pre><code>Error in ndf$x : $ operator is invalid for atomic vectors.
  </code></pre>
  
  <p>Simplifying even further, I found subsetting alone (not applying the order function ) does not generate a dataframe object </p>
  
  <pre><code>ndf &lt;- df[df$x &lt; 5,]
  
  class(ndf)
  [1] "integer"
  </code></pre>
  
  <p>It turns out for the multicolumn dataframe that separating the ordering and the subsetting does work as expected</p>
  
  <pre><code>df &lt;- data.frame(x = sample(1:50), y = rnorm(50))
  
  ndf &lt;- df[order(df$x),]
  
  print(ndf[ndf$x &lt; 5, ])
  </code></pre>
  
  <p>and this solved my original problem, but led to two further questions:</p>
  
  <ol>
  <li>Why is the type of object returned, as described above based on the 1 column dataframe test case, not a dataframe? ( I appreciate a 1 column dataframe just contains a single vector but it's still wrapped in a dataframe ?)</li>
  <li>Is it possible to order and subset a multicolumn dataframe in 1 step?</li>
  </ol>