【问题标题】:Return data subset time frames within another timeframes?在另一个时间范围内返回数据子集时间范围?
【发布时间】:2012-08-05 23:30:25
【问题描述】:

子集xts 对象有很多很好的方法。例如,可以通过以下方式获取所有年、月、日的所有数据,但仅限于上午 9:30 到下午 4 点之间:

my_xts["T09:30/T16:00"]

或者您可以通过以下方式获得两个日期之间的所有观察结果:

my_xts["2012-01-01/2012-03-31"]

或者某个日期之前/之后的所有日期:

my_xts["/2011"]  # from start of data until end of 2011
my_xts["2011/"]  # from 2011 until the end of the data

如何获取所有年份仅特定月份的所有数据,或所有月份和年份仅特定日期的所有数据?是否存在任何其他子集化技巧?

【问题讨论】:

标签: r time-series subset xts


【解决方案1】:

您可以使用.index* 系列函数来获取特定月份或月份中的特定日期。有关功能的完整列表,请参阅 ?index。例如:

library(quantmod)
getSymbols("SPY")
SPY[.indexmon(SPY)==0]   # January for all years (note zero-based indexing!)
SPY[.indexmday(SPY)==1]  # The first of every month
SPY[.indexwday(SPY)==1]  # All Mondays

【讨论】:

  • 非常好。我从来不记得那些。
  • 我认为这对包作者来说尤其重要,因为他们将这些实用功能隐藏在一个点后面。
【解决方案2】:

时间子集有点隐藏,所以我理解它为什么会引发这样的问题。我知道的唯一其他“技巧”是lastfirst 函数,如果需要,您可以嵌套它们。例如这将获得前 3 周的最后 2 天。

last(first(my_xts, "3 weeks"), "2 days")

【讨论】:

    【解决方案3】:

    请注意,Windows 和 ubuntu 的 yearmon 日期格式的 xts 子集似乎有不同的行为。

    library(quantmod)
    library(xts)
    
    getSymbols("SPY", src="google", from = "2004-01-01")
    x1 <- SPY['2006-01/2007-12']
    
    x2 <- apply.monthly(x1,mean)
    x2['2006-01/2007-12']
    
    x3 <- as.xts(coredata(x2),order.by = as.yearmon(index(x2)))
    x3['2006-01/2007-12']
    

    x2 的结果在 windows 和 ubuntu 之间是一致的,因为格式是完整日期。但是,x3 在将日期转换为 yearmon 后,对于 windows 和 ubuntu 会产生不同的结果。

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多