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"))
嘗試[difftime](http://stat.ethz.ch/R-manual/R-devel/library/base/html/difftime.html)? – zx8754
使用data.tables進行滾動連接? – Roland
添加可重複的數據,以防有人想要去... – zx8754