我有两组(已排序的)POSIXct 时间序列,如下所示:
set.seed(123)
ll = sort(strptime("16/07/2015", format="%d/%m/%Y") + 10*3600 + 1:3600 + round(rnorm(3600), digits=3))
tt = sort(strptime("16/07/2015", format="%d/%m/%Y") + 10.2*3600 + 1:180*10 + round(rnorm(180), digits=3))
tplus = 0:180
where ll
实际上有一些 10^5 的观察结果,tt
10^3 - 10^4 和tplus
长度为 10^3。从tt
我构建了一个时间戳矩阵tt1
通过增加tplus
对每个观察tt
:
tt1 = t(sapply(tt, function(x) x+tplus))
对于每个时间戳,我想知道最近的观察结果是什么ll
(作为索引ll
)。我可以这样计算:
tt2 = apply(tt1, c(1,2), function(x) max(which(ll <= x)))
但这很慢,我必须进行这种计算大约 10^3 次,那么我怎样才能加快速度呢?鉴于ll
已排序并且tt1
沿着列和行排序我希望可能存在一些东西。
看一下数据:
> head(ll)
[1] "2015-07-16 10:00:00.440 CEST" "2015-07-16 10:00:01.769 CEST" "2015-07-16 10:00:04.071 CEST" "2015-07-16 10:00:04.559 CEST"
[5] "2015-07-16 10:00:05.128 CEST" "2015-07-16 10:00:06.734 CEST"
> head(tt1[,1:4])
[,1] [,2] [,3] [,4] ...
[1,] 1437034330 1437034331 1437034332 1437034333
[2,] 1437034341 1437034342 1437034343 1437034344
[3,] 1437034350 1437034351 1437034352 1437034353
[4,] 1437034359 1437034360 1437034361 1437034362
[5,] 1437034371 1437034372 1437034373 1437034374
[6,] 1437034381 1437034382 1437034383 1437034384
以及预期的输出:
> head(tt2)
[,1] [,2] [,3] [,4] ...
[1,] 729 729 731 732
[2,] 740 741 742 743
[3,] 748 749 751 752
[4,] 759 760 760 762
[5,] 770 772 773 774
[6,] 780 781 783 785