title: R - using apply to compare previous rows
body: <p>So I have a dataframe from which I'd like to pull out rows that have the same name in column 2. For each set of duplicated rows with the same name, I'd then like to keep only the row with the highest value if it's score is 2 greater than the other duplicates. So in this example, I want to keep row 2 but not row 5. </p>
  
  <pre><code>&gt;df &lt;- data.frame(score=c(1,5,1,3,3),name=c("A1","A1","A2","A3","A3"))
  &gt;df
  score name
   1    A1
   5    A1
   1    A2
   3    A3
   3    A3
  </code></pre>
  
  <p>I can almost do what I want to happen with a for loop and make a little matrix of "dup" vs "keep" to then use to pull out the rows of the dataframe that satisfy both conditions.</p>
  
  <pre><code>&gt;test &lt;- matrix(ncol=1,nrow=nrow(df))
  &gt;for(i in 1:nrow(df)){ifelse((df[i,"name"] == df[i-1,"name"]) &amp;&amp; (df[i,"score"] &gt;= (df[i-1,"score"] + 2)),test[i] &lt;- "keep",test[i] &lt;- "dup")}
  &gt; test
       [,1]  
  [1,] NA    
  [2,] "keep"
  [3,] "dup" 
  [4,] "dup" 
  [5,] "dup"
  &gt;df[which(test[,1] == "keep"),]
      score name
  2     5   A1
  </code></pre>
  
  <p>Which works (apart from the first one), but is obviously ugly and slow as hell. I know there must be a way to do this with some version of apply, but I couldn't work out how to specify the previous row in the function. The actual dataframe is huge, so any tidier way would be great.</p>
  
  <p>Eventually I want the function to also keep rows that have a unique name too, so if this could be incorporated into the same function, I'd be very happy! </p>
  
  <p>Thanks in advance for any help....</p>