title: Searching for nearest date in data frame
body: <p>I have two data frames:</p>
  
  <pre><code>purchases:
  
                  time        quantity
    1: 2013-07-31 03:42:02    30       
    2: 2013-07-31 03:59:32    30        
    3: 2013-07-31 04:02:22    28       
    ....
  
  history:
  
                  time        price
    1: 2013-07-31 04:26:46   10
    2: 2013-07-31 07:11:01    10
    3: 2013-07-31 08:16:36     5
    4: 2013-07-31 08:40:03     8
    5: 2013-07-31 08:47:56     7
    ....
  </code></pre>
  
  <p>What I want to do:
  for each row in 'purchases', look up in 'history' the row with closest date (if possible smaller that the one in 'purchases')</p>
  
  <p>I was trying to do something like this</p>
  
  <pre><code>history &lt;- as.vector(history$time)
  </code></pre>
  
  <p>for each row in purchases:</p>
  
  <pre><code>current.price &lt;- purchases[i,]$time
  which(history-current.price)==min(history-current.price)
  </code></pre>
  
  <p>This is useful if the values are numeric, but I don't know how to handle theses dates of class POSIXct.</p>
  
  <p><strong>EDIT</strong>: added reproducible data</p>
  
  <pre><code>#Reproducible dummy data
  p &lt;- read.table(text="
  t,quantity
  2013-07-31 03:42:02,30
  2013-07-31 03:59:32,30
  2013-07-31 04:02:22,28",header=TRUE,sep=",")
  h &lt;- read.table(text="
  t,price
  2013-07-31 04:26:46,10
  2013-07-31 07:11:01,10
  2013-07-31 08:16:36,5
  2013-07-31 08:40:03,8
  2013-07-31 08:47:56,7",header=TRUE,sep=",")
  #Convert to POSIXct
  p$t &lt;- as.POSIXct(strptime(p$t, "%Y-%m-%d %H:%M:%S"))
  h$t &lt;- as.POSIXct(strptime(h$t, "%Y-%m-%d %H:%M:%S"))
  </code></pre>