2014-02-06 32 views
3

我有兩個數據幀:搜索在數據幀最近的日期

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

我想要做什麼: 在「購買」的每一行,在「歷史」與最接近的日期行查找(如果可能的話小的是一個在「購買」)

我是想在購買每一行做這樣的事情

history <- as.vector(history$time) 

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

如果這些值是數字,這很有用,但我不知道如何處理類POSIXct的這些日期。

EDIT:加入再生的數據

#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")) 
+0

嘗試[difftime](http://stat.ethz.ch/R-manual/R-devel/library/base/html/difftime.html)? – zx8754

+1

使用data.tables進行滾動連接? – Roland

+1

添加可重複的數據,以防有人想要去... – zx8754

回答

3

下面是使用difftime溶液。我已經更新了您的示例,並在日曆表中的日期後面添加了一些行。

#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)