【问题标题】:Subset xts object by time of day按一天中的时间子集 xts 对象
【发布时间】:2012-12-04 10:30:46
【问题描述】:

一个简单的问题:我知道如何在xts 中对时间序列进行子集化处理:x['2000-05/2001'] 等等。

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

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

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

【问题讨论】:

  • 你能举一个可重现的例子吗?
  • 如果你的 xts 对象被称为 x ,那么像 y <- x["T09:30/T11:00"] 这样的东西可以让我获得早上会议的一部分。
  • @agstudy sample.time = timeDate('2012-01-01 00:00:00')+15*60*(1:500) data = 1:500 data.ts = xts( data,order.by=sample.time) data.ts["T09:30/T11:00"]
  • @SlowLearner 你是对的.. 它只是工作......我很困惑,因为我只是在时间索引上使用它而不是在 xts 对象上。应用于对象它只是工作。 data.ts["T09:30/T11:00"] 有效,但 sample.time["T09:30/T11:00"] 无效。
  • @SlowLearner ...如果您的评论是答案,我会接受。 ...

标签: r time time-series xts


【解决方案1】:

例如,如果您的 xts 对象被称为 x,那么像 y <- x["T09:30/T11:00"] 这样的东西可以让我获得早上会议的一部分。

【讨论】:

    【解决方案2】:

    由于某种原因,使用x["T09:30/T11:00"] 来减少xts 时间非常慢,我使用R: Efficiently subsetting dataframe based on time of daydata.table time subset vs xts time subset 中的方法来使用类似的语法创建一个更快的函数:

    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)
    

    【讨论】:

    • 感谢您演示 xts 的时间子集可以多快!我已经created an issue 努力改进它。
    • 对于那些想知道的人......上面的自定义函数仍然比内部 xts 函数快约 1000 倍。
    • @ricardo:我得到的结果快了数百倍,但还没有接近 1000 倍。你能分享你的基准和sessionInfo() 输出吗?请随时通过电子邮件发送给我。
    猜你喜欢
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2013-03-15
    • 2017-07-27
    • 2017-12-01
    • 2014-04-12
    • 1970-01-01
    相关资源
    最近更新 更多