r语言 - 按一天中的时间划分的子集 xts 对象



一个简单的问题:我知道如何从帮助中对xts中的时间序列进行年、月和日的子集:x['2000-05/2001']等等。

但是,如何按一天中的小时对数据进行子集化呢?我想在上午 07:00 至下午 06:00 之间获取所有数据,即我想在工作时间提取数据 - 与当天无关(我稍后会照顾周末)。帮助有一个表单示例:

.parseISO8601('T08:30/T15:00')

但这在我的情况下不起作用。有人知道吗?

例如,如果您的xts对象被调用x那么像y <- x["T09:30/T11:00"]这样的东西可以帮助我获取上午会话的一部分。

出于某种原因,使用 x["T09:30/T11:00"] 缩短 xts 一天中的时间非常慢,我使用 R 中的方法: 根据一天中的时间和 data.table 时间子集与 xts 时间子集有效地对数据帧进行子集化,以使用类似的语法制作更快的函数:

cut_time_of_day <- function(x, t_str_begin, t_str_end){
    tstr_to_sec <- function(t_str){
        #"09:00:00" to sec of day
        as.numeric(as.POSIXct(paste("1970-01-01", t_str), "UTC")) %% (24*60*60)
    }
    #POSIX ignores leap second
    #sec_of_day = as.numeric(index(x)) %% (24*60*60)                                #GMT only
    sec_of_day = {lt = as.POSIXlt(index(x)); lt$hour *60*60 + lt$min*60 + lt$sec}   #handle tzone
    sec_begin  = tstr_to_sec(t_str_begin)
    sec_end    = tstr_to_sec(t_str_end)
    return(x[ sec_of_day >= sec_begin & sec_of_day <= sec_end,])
}

测试:

n = 100000
dtime <- seq(ISOdate(2001,1,1), by = 60*60, length.out = n)
attributes(dtime)$tzone <- "CET"
x = xts((1:n), order.by = dtime)
y2 <- cut_time_of_day(x,"07:00:00", "09:00:00")
y1 <- x["T07:00:00/T09:00:00"]
identical(y1,y2)

最新更新