R - 时间序列中的下一个最高值

R - Next highest value in a time series

一个相对简单的问题,但我似乎找不到任何例子。

我有一个简单的外汇价格数据,它位于一个名为 subx1 的 2 列 xts 对象中:

Datetime, Price   
2016-09-01 00:00:01, 1.11563  
2016-09-01 00:00:01, 1.11564  
2016-09-01 00:00:02, 1.11564  
2016-09-01 00:00:03, 1.11565

...等等。

我试图找到下午 2 点之后价格首次高于下午 2 点前高点的时间,该高点保存在另一个名为 daypeakxts$before2.High 和

的对象的列中

daypeakxts 的样本是:

Date, before2.High  
2016-09-01, 1.11567    
2016-09-02, 1.11987

这是我尝试做的一个糟糕的例子:

subxresult <- index(subx1, subx1$datetime > daypeakxts$before2.High)

...所以我希望在另一个 xts 对象中使用条件语句和一天的值来发现价格的日期时间。

您没有为reproducible example提供足够的数据,所以我将使用xts包附带的一些日常数据。

library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix, dateForamt = "Date")

# Aggregate and find the high for each week
Week.High <- apply.weekly(x, function(x) max(x$High))

# Finding the pre-2pm high would be something like:
# Pre.2pm.High <- apply.daily(x["T00:00/T14:00"], function(x) max(x$High))

# Merge the period high with the original data, and
# fill NA with the last observation carried forward
y <- merge(x, Week.High, fill = na.locf)

# Lag the period high, so it aligns with the following period
y$Week.High <- lag(y$Week.High)

# Find the first instance where the next period's high
# is higher than the previous period's high
y$First.Higher <- apply.weekly(y, function(x) which(x$High > x$Week.High)[1])