title: R dplyr select row of minimum date difference between two separate events
body: <p>I am working with a data set that includes roughly 400 unique subjects. for this example I will only be working with two however. You can generate sample data with this code:</p>
  
  <pre><code>set.seed(100)
  library(tidyr)
  library(dplyr)
  Subject&lt;-c("A","A","A","A","A","A","B","B","B","B")
  Event1&lt;-c("01/01/2001","01/01/2001","01/01/2001","01/01/2001","09/09/2001","09/09/2001","09/09/2009","09/09/2009","09/09/2009","09/09/2009")
  
  random.dates&lt;-function(N,sd="2001-01-01",ed="2010-01-01"){
      sd&lt;-as.Date(sd,"%Y-%m-%d")
      ed&lt;-as.Date(ed,"%Y-%m-%d")
      dt&lt;-as.numeric(difftime(ed,sd))
      ev&lt;-sort(runif(N,0,dt))
      rt&lt;-sd+ev
  }
  Event1&lt;-as.Date(Event1,"%m/%d/%Y")
  Event1
  Event2&lt;-print(random.dates(10))
  
  df&lt;-data.frame(Subject,Event1,Event2)
  df
  </code></pre>
  
  <p>and produces something close to this output of output:</p>
  
  <pre><code>   Subject     Event1     Event2
  1        A 2001-01-01 2001-05-04
  2        A 2001-01-01 2001-09-24
  3        A 2001-01-01 2002-10-22
  4        A 2001-01-01 2003-02-25
  5        A 2001-09-09 2007-07-16
  6        A 2001-09-09 2008-04-06
  7        B 2009-09-09 2008-07-12
  8        B 2009-09-09 2008-07-24
  9        B 2009-09-09 2009-04-01
  10       B 2009-09-09 2009-09-11
  </code></pre>
  
  <p>In this case I am interested in first grouping unique Subjects with unique Event1's which I can do easily. From there I need to select Event2 that falls closest to Event1 for that unique Subject-Event1 combination, which I really need help with. For this example these data should decompose to 3 different records:</p>
  
  <pre><code>   Subject     Event1     Event2
  1        A 2001-01-01 2001-05-04
  2        A 2001-09-09 2008-04-06
  3        B 2009-09-09 2009-09-11
  </code></pre>
  
  <p>I've jerry-rigged a solution to produce the 3 records of Subject-Event1 combinations:</p>
  
  <pre><code>df2&lt;-df
  df2$SubEv&lt;-paste(df2$Subject,df2$Event1)
  df2$Event1&lt;-NULL
  df2$Subject&lt;-NULL
  df2$Event2&lt;-NULL
  df2&lt;-unique(df2)
  df2&lt;-separate(df2,SubEv,c("Subject","Event1"),sep=" ")
  </code></pre>
  
  <p>From here I'm just lost as to how to make R select from df the date of Event2 that is closest to Event1.</p>
  
  <p>I already know that my code is super inefficient and sloppy (probably because of my approach at the get go). I'd like to know how to do this (at all honestly), and if there's a way I can do this calling fewer than 10 lines of code that would be pretty boss.</p>