【问题标题】:Preserve xts index when using rowSums on xts在 xts 上使用 rowSums 时保留 xts 索引
【发布时间】:2017-05-27 22:48:17
【问题描述】:

在传递rowSumsxts 对象时,有没有办法保留xts 对象的索引?

目前我将结果重新转换为 xts 对象,但如果 rowSums 能够简单地返回传递的内容,这似乎没有那么快。

xts(rowSums(abs(data)),index(data))

【问题讨论】:

    标签: r xts rowsum


    【解决方案1】:

    有趣的问题。让我们忽略abs 的计算,因为很多时候它与价格无关。如果您关心的是性能,以下是当前建议需要考虑的一组时间安排:

    library(microbenchmark)
    sample.xts <- xts(order.by = as.POSIXct("2004-01-01 00:00:00") + 1:1e6, matrix(rnorm(1e6 *4), ncol = 4), dimnames = list(NULL, c("A", "B", "C", "D")))
    
    # See how quickly rowSum works on just the underlying matrix of data in the timings below:
    xx <- coredata(sample.xts)
    
    microbenchmark(
        coredata(sample.xts),
        rowSums(xx),
        rowSums(sample.xts),
        rowSums(coredata(sample.xts)),
    .xts(x = rowSums(sample.xts), .index(sample.xts)),
    xts(rowSums(coredata(sample.xts)), index(sample.xts)),
    xts(rowSums(sample.xts),index(sample.xts)), 
    Reduce("+", as.list(sample.xts)), times = 100)
    
    # Unit: milliseconds
    #                                                  expr       min        lq      mean    median        uq       max neval
    #                                  coredata(sample.xts)  2.558479  2.661242  6.884048  2.817607  6.356423 104.57993   100
    #                                           rowSums(xx) 10.314719 10.824184 11.872108 11.289788 12.382614  18.39334   100
    #                                   rowSums(sample.xts) 10.358009 10.887609 11.814267 11.335977 12.387085  17.16193   100
    #                         rowSums(coredata(sample.xts)) 12.916714 13.839761 18.968731 15.950048 17.836838 113.78552   100
    #     .xts(x = rowSums(sample.xts), .index(sample.xts)) 14.402382 15.764736 20.307027 17.808984 19.072600 114.24039   100
    # xts(rowSums(coredata(sample.xts)), index(sample.xts)) 20.490542 24.183286 34.251031 25.566188 27.900599 125.93967   100
    #           xts(rowSums(sample.xts), index(sample.xts)) 17.436137 19.087269 25.259143 21.923877 22.805013 119.60638   100
    #                      Reduce("+", as.list(sample.xts)) 21.745574 26.075326 41.696152 27.669601 30.442397 136.38650   100
    
    y = .xts(x = rowSums(sample.xts), .index(sample.xts))
    y2 = xts(rowSums(sample.xts),index(sample.xts))
    all.equal(y, y2)
    #[1] TRUE
    

    coredata(sample.xts) 返回底层数字矩阵。我认为rowSums(xx) 给出了您可以期望的最快性能,用于进行计算,这可以被视为“基准”。那么问题来了,在xts 对象中最快的方法是什么。它似乎 .xts(x = rowSums(sample.xts), .index(sample.xts)) 表现不错。

    【讨论】:

    • 感谢乔希的快速周到的回复。
    • @theGreatKatzul:这是 FXQuantTrader 的回复。我唯一的贡献是对齐微基准输出中的标题。
    【解决方案2】:

    如果您的反对意见是必须将输入的组件分开并放在一起,那么如果 x 是您的 xts 对象,那么试试这个。它直接返回一个 xts 对象:

    Reduce("+", as.list(x))
    

    【讨论】:

    • 感谢您的回复。我主要关心的是整洁,因为调用已经存在于 lapply lambda 函数中。
    猜你喜欢
    • 2011-03-24
    • 2011-05-25
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2015-10-30
    • 1970-01-01
    相关资源
    最近更新 更多