使用参数保持日期在xts中进行子集化

时间:2012-12-31 12:36:34

标签: r subset xts

我熟悉xts子集化功能。但是,我找不到一种优雅的方法来对参数化日期范围进行子集化。像这样的东西:

times = c(as.POSIXct("2012-11-03 09:45:00 IST"),
          as.POSIXct("2012-11-05 09:45:00 IST"))

#create an xts object:
xts.obj = xts(c(1,2),order.by = times)

#filter with these dates:
start.date = as.POSIXct("2012-11-03")
end.date = as.POSIXct("2012-11-04")

#instead of xts["2012-11-03"/"2012-11-04"], do something like this:
xts[start.date:end.date]

有人有任何想法吗?谢谢!

4 个答案:

答案 0 :(得分:7)

您可以将start.dateend.date个对象粘贴在一起,按"::""/"分隔,然后将其用于子集。

R> xts.obj[paste(start.date,end.date,sep="::")]
                    [,1]
2012-11-03 09:45:00    1

答案 1 :(得分:2)

[.xts {xts}

的帮助下
  

由于xts使用所有用户级索引的POSIXct时间表示   在内部类,最快的基于时间的子集将永远是   来自POSIXct对象,无论原始的indexClass如何   对象

所以你可以像这样做基于时间的子集:

xts.obj[seq(start.date,end.date,by=60)]
                    [,1]
2012-11-03 09:45:00    1

答案 2 :(得分:1)

对于那些正在绞尽脑汁为非Posix做这件事的人。特别是基于季度的数据,即2001年第二季度至2006年第三季度。

我使用了一个简单而优雅的解决方案:

library(xts)

starting.quarter<-"200101"
ending.quarter<-"201702"

oil_price_by_qtr<-oil_price_by_qtr[paste(starting.quarter,ending.quarter,sep="/")]

这将从2001年第一季度到2017年第二季度将XTS对象分组。

这可以帮助其他一些可怜的人避免失去2小时的生命。

答案 3 :(得分:0)

我只需要做同样的事情。这是我的解决方案,基于原始示例。

library(xts)

times = c(as.POSIXct("2012-11-03 09:45:00 IST"),
          as.POSIXct("2012-11-05 09:45:00 IST"))

#create an xts object:
xts.obj = xts(c(1,2),order.by = times)

#filter with these dates:
start.date = as.POSIXct("2012-11-03")
end.date = as.POSIXct("2012-11-04")

# By using an index that is the logical AND of two vectors
xts.obj[start.date <= index(xts.obj) & index(xts.obj) <= end.date]