您可以考虑将时间序列转换为xts-对象,以便更轻松地进行数据操作。例如,我们可以使用.indexwkday从xts-object 中提取工作日:
library(xts)
## load data
data(taylor, package = "forecast")
## convert to xts
taylor_xts <- xts(
x = taylor,
order.by = seq(from = as.POSIXct("2000-06-05"), length = length(taylor), by = "30 min")
)
## extract weekdays
taylor_wk <- taylor_xts[.indexwday(taylor_xts) %in% 1:5]
head(taylor_wk); tail(taylor_wk)
#> [,1]
#> 2000-06-05 00:00:00 22262
#> 2000-06-05 00:30:00 21756
#> 2000-06-05 01:00:00 22247
#> 2000-06-05 01:30:00 22759
#> 2000-06-05 02:00:00 22549
#> 2000-06-05 02:30:00 22313
#> [,1]
#> 2000-08-25 21:00:00 33064
#> 2000-08-25 21:30:00 31953
#> 2000-08-25 22:00:00 30548
#> 2000-08-25 22:30:00 29236
#> 2000-08-25 23:00:00 27623
#> 2000-08-25 23:30:00 26063
或者,如果我们希望仅提取办公时间(工作日上午 9 点至下午 6 点)的数据:
## extract office hours
taylor_offh <- taylor_xts[.indexwday(taylor_xts) %in% 1:5 & .indexhour(taylor_xts) >= 9 & .indexhour(taylor_xts) < 18]
head(taylor_offh); tail(taylor_offh)
#> [,1]
#> 2000-06-05 09:00:00 36834
#> 2000-06-05 09:30:00 37296
#> 2000-06-05 10:00:00 37338
#> 2000-06-05 10:30:00 37608
#> 2000-06-05 11:00:00 37692
#> 2000-06-05 11:30:00 37944
#> [,1]
#> 2000-08-25 15:00:00 35067
#> 2000-08-25 15:30:00 34928
#> 2000-08-25 16:00:00 34738
#> 2000-08-25 16:30:00 35004
#> 2000-08-25 17:00:00 34748
#> 2000-08-25 17:30:00 34090
注意:使用plot.xts 绘制子采样时间序列会在 x 轴上显示日期时间,因此包括周末的间隙,(因为不再定期对时间序列进行采样)。要将数据绘制为串联系列,请使用plot.default(或转换回ts 对象后的plot.ts)。
## plot time-series along time
plot(taylor_wk)
## plot time-series along index
plot.default(taylor_wk, type = "l") ## equivalently `plot(coredata(taylor_wk), type = "l")`