title: Stata: Deleting duplicates based on dates
body: <p>My dataset consists of a number of variables:</p>
  
  <pre><code>* Example generated by -dataex-. To install: ssc install dataex
  clear
  input float(v1 v2) str11 Date float(v4 v5 v6 v7 v8)
  1 2 "15-aug-2016" 1 1 1 1  1
  1 2 "07-may-2015" 1 1 1 1 50
  1 2 "07-may-2015" 1 1 1 1 88
  1 2 "15-aug-2016" 1 1 1 1 29
  end
  </code></pre>
  
  <p>The variable <code>date</code> is a date and time and is formatted as a datetime </p>
  
  <p><code>generate double date = date(Date,"DMY")</code></p>
  
  <p>My duplicates are the same for v1-v2-v4-v5-v6-v7 (as in the example), while v8 is different.</p>
  
  <p>I need to delete duplicates based on v1-v2-v4-v5-v6-v7 and keep the one with the smallest date (here 07-may-2015). </p>
  
  <p>I have tried without success: </p>
  
  <p>1.</p>
  
  <pre><code>gsort -date
  bysort v1 v2 v4 v5 v6 v7: generate dublet=_n
  order dublet date
  keep if dublet==1
  drop dublet
  </code></pre>
  
  <p>--> Works for the first 25 rows or so, then keeps the wrong one a couple of times and then the right one again. (Seems to me, that the <code>bysort</code> command removes the sort done by <code>gsort</code>? Any knowing if that's correct?)</p>
  
  <ol start="2">
  <li><p><code>bysort v1 v2 v4 v5 v6 v7 (date) : keep if _n == _N</code></p></li>
  </ol>
  
  <p>--> Obviously keeps the wrong one, since <code>Date</code> is not <code>-Date</code>. 
  However, <code>-Date</code> is not an option - Stata writes: <code>- invalid name</code></p>