title: R - Keep first observation per group identified by multiple variables (Stata equivalent "bys var1 var2 : keep if _n == 1")
body: <p>So I currently face a problem in R that I exactly know how to deal with in Stata, but have wasted over two hours to accomplish in R.</p>
  
  <p>Using the data.frame below, the result I want is to obtain exactly the first observation per group, while groups are formed by multiple variables and have to be sorted by another variable, i.e. the data.frame mydata obtained by:</p>
  
  <pre><code>id &lt;- c(1,1,1,1,2,2,3,3,4,4,4)
  day &lt;- c(1,1,2,3,1,2,2,3,1,2,3)
  value &lt;- c(12,10,15,20,40,30,22,24,11,11,12)
  mydata &lt;- data.frame(id, day, value)
  </code></pre>
  
  <p>Should be transformed to:</p>
  
  <pre><code>   id day value   
     1   1    10 
     1   2    15 
     1   3    20 
     2   1    40 
     2   2    30 
     3   2    22 
     3   3    24 
     4   1    11 
     4   2    11 
     4   3    12 
  </code></pre>
  
  <p>By keeping only one of the rows with one or multiple duplicate group-identificators (here that is only <code>row[1]: (id,day)=(1,1))</code>, sorting for value first (so that the row with the lowest value is kept).</p>
  
  <p>In Stata, this would simply be:</p>
  
  <pre><code>bys id day (value): keep if _n == 1
  </code></pre>
  
  <p>I found a <a href="http://www.ats.ucla.edu/stat/r/faq/firstlast.htm" rel="noreferrer">piece of code on the web</a>, which properly does that if I first produce a single group identifier :</p>
  
  <pre><code>mydata$id1 &lt;- paste(mydata$id,"000",mydata$day, sep="")  ### the single group identifier
  
  myid.uni &lt;- unique(mydata$id1)
  a&lt;-length(myid.uni)
  
  last &lt;- c()
  
  for (i in 1:a) {
    temp&lt;-subset(mydata, id1==myid.uni[i])
    if (dim(temp)[1] &gt; 1) {
      last.temp&lt;-temp[dim(temp)[1],]
    }
    else {
      last.temp&lt;-temp
    }
    last&lt;-rbind(last, last.temp)
  }
  
  last
  </code></pre>
  
  <p>However, there are a few problems with this approach:<br>
  1. A single identifier needs to be created (which is quickly done).<br>
  2. It seems like a cumbersome piece of code compared to the single line of code in Stata.<br>
  3. On a medium-sized dataset (below 100,000 observations grouped in lots of about 6), this approach would take about 1.5 hours.</p>
  
  <p>Is there any efficient equivalent to Stata's <code>bys var1 var2: keep if _n == 1</code> ?</p>