R xts:查询日期和时间

时间:2012-02-21 16:06:11

标签: r xts

我无法查询xts是否包含日期和时间范围的子集。例如:

> head(myxts['2012-01-06 9:30:00/2012-01-06 10:00:00'], 1)
                    Symbol       
2012-01-03 09:30:00 "AA"

> tail(myxts['2012-01-06 9:30:00/2012-01-06 10:00:00'], 1)
                Symbol       
2012-01-06 10:00:00 "AA"

这里的第一行是2012-01-03。为什么不2012-01-06?

修改

我还尝试先将一个日期提取到一个新变量,然后按时间查询。在这种情况下,正确提取日期时间序列,但时间子集不起作用。

e = myxts['2012-01-06']
e['10:00:00::10:20:00'] # returns all rows in '2012-01-06'

编辑2

发现这种情况,输入'09:45:00'而不是'9:45:00'似乎解决了问题:

> tail(myxts['2011-12-19 9:40:00::2011-12-19 9:45:00'])
                    Symbol DaySec
2011-12-19 16:00:00 "WPI"  "57600"

> tail(myxts['2011-12-19 9:40:00::2011-12-19 09:45:00'])
                    Symbol DaySec  
2011-12-19 09:45:00 "WPI"  "35100"

2 个答案:

答案 0 :(得分:1)

'2012-01-06 9:30:00'不符合ISO-8601标准。每次组件必须是两位数(如果指定),因此您需要'2012-01-06 09:30:00'

答案 1 :(得分:0)

适合我:

R> now <- Sys.time()
R> foo <- xts(1:100, now + (1:100)*30*60)   # hundred half-hour intervals
R> head(foo)
                          [,1]
2012-02-21 11:48:32.37683    1
2012-02-21 12:18:32.37683    2
2012-02-21 12:48:32.37683    3
2012-02-21 13:18:32.37683    4
2012-02-21 13:48:32.37683    5
2012-02-21 14:18:32.37683    6
R> tail(foo)
                          [,1]
2012-02-23 10:48:32.37683   95
2012-02-23 11:18:32.37683   96
2012-02-23 11:48:32.37683   97
2012-02-23 12:18:32.37683   98
2012-02-23 12:48:32.37683   99
2012-02-23 13:18:32.37683  100

现在我们可以从2月21日的最后一小时开始,直到2月23日的第一个小时:

R> xtract <- foo["2012-02-21 23:00::2012-02-23 01:00"]
R> head(xtract)
                          [,1]
2012-02-21 23:18:32.37683   24
2012-02-21 23:48:32.37683   25
2012-02-22 00:18:32.37683   26
2012-02-22 00:48:32.37683   27
2012-02-22 01:18:32.37683   28
2012-02-22 01:48:32.37683   29
R> tail(xtract)
                          [,1]
2012-02-22 22:18:32.37683   70
2012-02-22 22:48:32.37683   71
2012-02-22 23:18:32.37683   72
2012-02-22 23:48:32.37683   73
2012-02-23 00:18:32.37683   74
2012-02-23 00:48:32.37683   75
R> 

我也可以在一天内提取:

R> xtract <- foo["2012-02-23 02:00::2012-02-23 04:00"]
R> xtract
                          [,1]
2012-02-23 02:18:32.37683   78
2012-02-23 02:48:32.37683   79
2012-02-23 03:18:32.37683   80
2012-02-23 03:48:32.37683   81
R>