title: efficient use of R data.table and unique()
body: <p>Is there a more efficient query than the following</p>
  <pre><code>DT[, list(length(unique(OrderNo)) ),customerID]
  </code></pre>
  <p>to refine a LONG format table with customer id's, order number and product line items, meaning that there will be duplicate rows with the same order id if a customer has purchased more than 1 item in that transaction.</p>
  <p>Trying to work out unique purchases. <code>length()</code> gives a count of all order id's by customer ID including duplicates, looking for just the unique number.</p>
  <h1>Edit from here:</h1>
  <p>Here is some dummy code. Ideally what i am looking for is the output from the first query using the <code>unique()</code>.</p>
  <pre><code>df &lt;- data.frame(
               customerID=as.factor(c(rep(&quot;A&quot;,3),rep(&quot;B&quot;,4))),
               product=as.factor(c(rep(&quot;widget&quot;,2),rep(&quot;otherstuff&quot;,5))),
               orderID=as.factor(c(&quot;xyz&quot;,&quot;xyz&quot;,&quot;abd&quot;,&quot;qwe&quot;,&quot;rty&quot;,&quot;yui&quot;,&quot;poi&quot;)),
               OrderDate=as.Date(c(&quot;2013-07-01&quot;,&quot;2013-07-01&quot;,&quot;2013-07-03&quot;,&quot;2013-06-01&quot;,&quot;2013-06-02&quot;,&quot;2013-06-03&quot;,&quot;2013-07-01&quot;))
               )
  
  DT.eg &lt;- as.data.table(df)
  #Gives unique order counts
  DT.eg[, list(orderlength = length(unique(orderID)) ),customerID]
  #Gives counts of all orders by customer
  DT.eg[,.SD, keyby=list(orderID, customerID)][, .N, by=customerID]
  
           ^
           |
    This should be .N, not .SD  ~ R.S.
  </code></pre>