【问题标题】:R - Next highest value in a time seriesR - 时间序列中的下一个最高值
【发布时间】:2017-09-22 17:50:06
【问题描述】:

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

我有一个简单的外汇价格数据,它位于一个名为 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 对象中使用带有一天值的条件语句来发现价格的日期时间。

【问题讨论】:

  • 尝试使用 which.max(time &gt; 2PM &amp; value &gt; earlierValue) 之类的内容和适当的翻译。
  • 谢谢。我必须转换为常规 data.frame,然后尝试: subxresult daypeakxts$before2.High) 但收到错误:“更长的对象长度是不是较短对象长度的倍数”我在一个实例中使用日期(对于当天下午 2 点前的最高价格),但主要时间序列的日期时间。两者都是 POSIX 格式。

标签: r time-series xts zoo


【解决方案1】:

您没有为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])

【讨论】:

  • 我尝试了您的解决方案。它适用于您的示例 - 并且已经非常适应。
猜你喜欢
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
相关资源
最近更新 更多