Finding the closest date in a data frame

I have two data frames:

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
  ....

What I want to do: for each line in the “purchases”, find in the “history” the line with the nearest date (if possible less than in the “purchases”)

I tried to do something like this

history <- as.vector(history$time)

for each line of purchases:

current.price <- purchases[i,]$time
which(history-current.price)==min(history-current.price)

This is useful if the values ​​are numeric, but I do not know how to handle the POSIXct class date abstract.

EDIT : Added playable data

#Reproducible dummy data
p <- 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 <- 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 <- as.POSIXct(strptime(p$t, "%Y-%m-%d %H:%M:%S"))
h$t <- as.POSIXct(strptime(h$t, "%Y-%m-%d %H:%M:%S"))
+3
source share
1 answer

Here is a solution using difftime. I updated your example to have multiple rows with dates lower than in the history table.

#Reproducible dummy data
p <- 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
2013-07-31 04:40:22,28
2013-07-31 05:50:22,28
2013-07-31 08:40:22,28",header=TRUE,sep=",")
h <- read.table(text="
t,price
2013-07-31 04:10:46,10
2013-07-31 04:35: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 <- as.POSIXct(strptime(p$t, "%Y-%m-%d %H:%M:%S"))
h$t <- as.POSIXct(strptime(h$t, "%Y-%m-%d %H:%M:%S"))


get_closest_line_in_history <- function(x, history){
  time_diffs <- difftime(x, history)
  time_diffs[time_diffs<0] <- NA

  res <- which.min(time_diffs)
  if (length(res) != 1){
    return(NA)
  }else{
    return(res)
  }
}

sapply(p$t, get_closest_line_in_history, h$t)
+3
source

All Articles