title: using data.table to flag the first (or last) record in a group
body: <p>Given a sortkey, is there a data.table shortcut to duplicate the <code>first</code> and <code>last</code> functionalities found in SAS and SPSS ?</p>
  
  <p>The pedestrian approach below flags the first record of a group. </p>
  
  <p>Given the elegance of data.table (with which I'm slowly getting familiar), I'm assuming there's a shortcut using a self join &amp; <code>mult</code>, but I'm still trying to figure it out. </p>
  
  <p>Here's the example:</p>
  
  <pre><code>require(data.table)
  
  set.seed(123)
  n &lt;- 17
  DT &lt;- data.table(x=sample(letters[1:3],n,replace=T),
                   y=sample(LETTERS[1:3],n,replace=T))
  sortkey  &lt;- c("x","y")
  setkeyv(DT,sortkey)
  key &lt;- paste(DT$x,DT$y,sep="-")
  nw &lt;- c( T , key[2:n]!=key[1:(n-1)] )
  DT$first &lt;- 1*nw
  DT
  </code></pre>