title: select last row by group with "collapse (last) ..." syntax
body: <p>I want to select the last row in each subset of the data determined by one or more categorical variables.</p>
  
  <hr>
  
  <p><em>Background.</em> For each ticket in my data set, I have a <code>ticketid</code> and multiple transactions (sale, refund, sale, refund, sale...). I am only interested in keeping series that end in "sale".</p>
  
  <p>My first step was to drop <code>ticketid</code>s with evenly matched sales and refunds:</p>
  
  <pre><code>duplicates tag ticketid, gen(mult)
  by ticketid: egen count_sale = total(transtatus == "Sale")
  by ticketid: egen count_ref  = total(transtatus == "Refund")
  
  drop if mult &amp; count_sale == count_ref
  </code></pre>
  
  <p>Now, I want to keep just the final sale when <code>count_sale = count_ref + 1</code></p>
  
  <pre><code>sort ticketid time
  preserve
    ** some collapse command
  
    save "temp_terminal_sales.dta"
  restore
  append using "temp_terminal_sales.dta"
  </code></pre>
  
  <p>I can't figure out how (if at all) to use <code>collapse</code> here. I think I may just have to <code>keep if mult</code>, tag the last row with <code>by ticketid: gen last = _n == _N</code> and <code>keep if last</code>...? It seems like collapse should work. Here is the (wrong) syntax that seemed intuitive to me:</p>
  
  <pre><code>collapse (last), by(ticketid)
  collapse (last) *, by(ticketid)
  </code></pre>
  
  <p>These don't work because (i) a <code>varlist</code> is required, and (ii) the <code>by</code> variables cannot be in the <code>varlist</code>.</p>
  
  <hr>
  
  <p>Example data:</p>
  
  <pre><code>ticketid time myvar transtatus
  1        1    2     "Sale"
  1        2    2     "Refund"
  2        1    2     "Sale"
  3        1    2     "Sale"
  3        2    2     "Refund"
  3        3    2     "Sale"
  3        4    2     "Refund"
  4        1    2     "Sale"
  4        2    2     "Refund"
  4        3    2     "Sale"
  </code></pre>
  
  <p>Desired result:</p>
  
  <pre><code>ticketid time myvar transtatus
  2        1    2     "Sale"
  4        3    2     "Sale"
  </code></pre>