xts 中的向量化有一个简单的解决方案吗

问题描述 投票:0回答:1
set.seed(2)
library(xts)

x <- sample(1:5,10,replace = T)
x.xts <- xts(x, order.by = seq(as.POSIXct(Sys.time()), length = 10, by = "min"))

我有 xts 对象

x.xts
,我想对他应用像这样的矢量化操作

x[1] > x

[1] FALSE  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE

但是当我这样做时,我得到的不是我所期望的

x.xts[1] > x.xts

                       e1
2023-12-06 10:13:16 FALSE

如果我将

x.xts[1]
转换为向量,我就能得到我想要的东西

as.vector(zoo::coredata(x.xts[1])) > x.xts

                     [,1]
2023-12-06 10:13:16 FALSE
2023-12-06 10:14:16  TRUE
2023-12-06 10:15:16 FALSE
2023-12-06 10:16:16  TRUE
2023-12-06 10:17:16  TRUE
2023-12-06 10:18:16 FALSE
2023-12-06 10:19:16  TRUE
2023-12-06 10:20:16  TRUE
2023-12-06 10:21:16  TRUE
2023-12-06 10:22:16  TRUE

但是这个

as.vector(zoo::coredata(x.xts[1]))
看起来很庞大,而且里面有很多转换,如果可能的话我想减少这个,因为我会多次运行代码。

有没有办法让表达式

as.vector(zoo::coredata(x.xts[1])) > x.xts
更接近
x.xts[1] > x.xts


而且表现看起来很糟糕

 f <- function(x.xts) { xx = as.vector(coredata(x.xts)); xx < xx[1L] }

> microbenchmark::microbenchmark(
+   x[1] > x , 
+   as.vector(zoo::coredata(x.xts[1])) > x.xts,
+   f(x.xts))
Unit: nanoseconds
                                       expr    min       lq     mean   median     uq     max neval
                                   x[1] > x    570   1141.0   2229.6   2281.0   2851    5702   100
 as.vector(zoo::coredata(x.xts[1])) > x.xts 526830 535382.5 565658.3 545075.5 562180  872919   100
                                   f(x.xts)  29078  30789.0 116358.9  34495.0  37916 8096878   100
> 
r xts
1个回答
0
投票

在速度提升方面,基本的“预计算”可能会有所帮助:

xx = as.vector(coredata(x.xts)); xx < xx[1L]
© www.soinside.com 2019 - 2024. All rights reserved.