从xts对象R中识别工作日和时间

时间:2016-04-25 20:40:01

标签: r xts

我是这样的xtc对象 x2

str(x2)

An ‘xts’ object on 2016-01-31 23:15:00/2016-02-26 22:55:00 containing:
  Data: num [1:5700, 1] 1.08 1.08 1.08 1.08 1.08 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "close"
  Indexed by objects of class: [POSIXct,POSIXt] TZ: America/New_York
  xts Attributes:  
 NULL


head(x2, 10)
                      close
2016-01-31 23:15:00 1.083390
2016-01-31 23:20:00 1.083350
2016-01-31 23:25:00 1.083125
2016-01-31 23:30:00 1.083360
2016-01-31 23:35:00 1.083240
2016-01-31 23:40:00 1.083190
2016-01-31 23:45:00 1.083165
2016-01-31 23:50:00 1.083020
2016-01-31 23:55:00 1.082965
2016-02-01 00:00:00 1.082200

现在我想确定例如从8:00到10:00的所有星期一。有一个明智的方法来获得这个吗?谢谢你们。

1 个答案:

答案 0 :(得分:2)

您可以使用.indexwday().indexhour()。下面是一个小例子:

library(xts)
seqTime <- seq(as.POSIXct("2016-01-01"), by = 300, length.out = 1000) 
myXts <- xts(rnorm(1000), seqTime)
myXts[.indexwday(myXts) == 1 & (.indexhour(myXts) %in% c(8, 9))]

带输出:

                           [,1]
2016-01-04 08:00:00  0.74224022
2016-01-04 08:05:00 -0.50372235
2016-01-04 08:10:00  0.94655985
2016-01-04 08:15:00 -0.80261212
2016-01-04 08:20:00  0.90475246
2016-01-04 08:25:00 -0.72225021
2016-01-04 08:30:00 -0.32635167
2016-01-04 08:35:00  0.94919253
2016-01-04 08:40:00  0.33799147
2016-01-04 08:45:00  1.19636284
2016-01-04 08:50:00  0.13022675
2016-01-04 08:55:00 -0.61397227
2016-01-04 09:00:00 -2.14580209
2016-01-04 09:05:00 -0.02778257
2016-01-04 09:10:00 -0.73649967
2016-01-04 09:15:00  0.31217192
2016-01-04 09:20:00 -0.30923692
2016-01-04 09:25:00  0.64499992
2016-01-04 09:30:00 -1.84125238
2016-01-04 09:35:00  2.43008526
2016-01-04 09:40:00 -1.85907819
2016-01-04 09:45:00  0.31648160
2016-01-04 09:50:00 -0.02847419
2016-01-04 09:55:00 -0.09911078