title: Selecting records with latest year using data.table in R
body: <p>I have a datatable where the same entity appears more than one time with a different date.</p>
  <p>My objective is to retain a single record for each entity, the one with the latest date.</p>
  <p>My code is not right though.  For a reproducible example see below:</p>
  <pre><code>data(mtcars)
  mtcars
  mtcars$model &lt;- row.names(mtcars)
  setDT(mtcars)
  mtcars[, year := 2000]
  mtcars1 &lt;- mtcars[sample(nrow(mtcars), 5) , ]
  mtcars1[, year := 2001]
  mtcars2 &lt;- mtcars[sample(nrow(mtcars), 5) , ]
  mtcars2[, year := 2002]
  mtcars &lt;- rbind(mtcars, mtcars1, mtcars2)
  setDT(mtcars)
  mtcars
  
  mtcars_latest &lt;- mtcars[year == max(year) , names(mtcars), with = FALSE , by = model]
  </code></pre>
  <p>With the last line I intend to group by model and then within each group select the record with the latest year (<code>year == max(year)</code>).  Moreover, I want all the variables (columns) of the original datatable to be returned, so I put names(mtcars), with = FALSE.</p>