在另一个时间范围内返回数据子集时间范围?

问题描述:

有非常好的方法子集xts对象。例如,一个可以得到所有的数据全部年,月,天,但被严格9:30 AM至下午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 

我怎样才能得到只有某些个月,所有年份的所有几个月和几年的所有数据,或者只有某些天?是否存在其他子集技巧?

+2

你见过quantmod.com吗?具体来说,示例http://www.quantmod.com/examples/data/ – GSee 2012-08-08 19:24:37

+0

以下是如何使用'which.i'来颠倒子集:http://stackoverflow.com/a/32029644/841830 – 2015-08-17 11:09:03

+0

对于一个year'dt''2009',]',过滤年份和月份'dt [':2009-01',]'并使用日期范围:'dt ['2009-01-01 :: 2009-02-01' ]'。 – marbel 2016-01-08 21:12:33

您可以使用.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 
+0

非常好。我从来不记得那些。 – GSee 2012-08-08 19:29:05

+12

我认为这是封装作者特别想要的,因为他们将这些实用功能隐藏在点后面。 – 2012-08-08 20:37:48

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

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

知道,有似乎是xts子集为Windows和Ubuntu的一个yearmon日期格式的不同的行为。

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之间是一致的,因为格式是全日期。但是,在将日期转换为yearmon之后,将对windows和ubuntu产生不同的结果。