title: Selecting rows and ordering the result in R
body: <p>The seemingly trivial task of selecting rows in a data frame and then ordering them is eluding me, and driving me crazy at the same time. For example, lets have a trivial data frame:</p>
  
  <pre><code>country = c("US", "US", "CA", "US")
  company = c("Apple", "Google", "RIM", "MS")
  vals = c(100, 70, 50, 90)
  df &lt;- data.frame(country, company, vals)
  </code></pre>
  
  <p>Lets order it by vals</p>
  
  <pre><code>&gt; df[order(vals),]
    country company vals
  3      CA     RIM   50
  2      US  Google   70
  4      US      MS   90
  1      US   Apple  100
  </code></pre>
  
  <p>Works perfectly. Lets now try to select only US companies, and order there values. We get some bogus result.</p>
  
  <pre><code>&gt; df[country=="US", ][order(vals),]
      country company vals
  4       US      MS   90
  2       US  Google   70
  NA    &lt;NA&gt;    &lt;NA&gt;   NA
  1       US   Apple  100
  </code></pre>
  
  <p>Lets order, and then select. Again, a bogus result</p>
  
  <pre><code>&gt; df[order(vals),][country=="US", ]
    country company vals
  3      CA     RIM   50
  2      US  Google   70
  1      US   Apple  100
  </code></pre>
  
  <p>How do I get a data frame, which only includes US companies, and is sorted by val?</p>