title: Filter dataframe by maximum values in each group
body: <p>I have a 180,000 x 400 dataframe where the rows correspond to users but every user has exactly two rows. </p>
  
  <pre><code>id   date  ...
  1    2012    ...
  3    2010    ...
  2    2013    ...
  2    2014    ...
  1    2011    ...
  3    2014    ...
  </code></pre>
  
  <p>I want to subset the data so that only the most recent row for each user is retained (i.e. the row with the highest value for date for each id).</p>
  
  <p>I first tried using <code>which()</code> looping <code>ids</code> with an <code>ifelse()</code> statement in <code>sapply()</code> which was painfully slow (<code>O(n^2)</code> I believe). </p>
  
  <p>Then I tried sorting the <code>df</code> by <code>id</code> and then looping through in increments of two and comparing adjacent dates but this was also slow (I guess because loops in R are hopeless). The comparison of the two dates is the bottleneck as the sort was pretty much instant.</p>
  
  <p>Is there a way to vectorize the comparison? </p>
  
  <p>SOLUTION from <a href="https://stackoverflow.com/q/12805964/4346952">Remove duplicates keeping entry with largest absolute value</a></p>
  
  <pre><code>aa &lt;- df[order(df$id, -df$date), ] #sort by id and reverse of date
  aa[!duplicated(aa$id),]
  </code></pre>
  
  <p>Runs very quickly!!</p>