合并大量的xts对象

Ale*_*lex 11 merge r list zoo xts

我有一个xts互相排列的对象列表.我想把merge列表变成一个大xts对象.我这样做的尝试是"

merged_reg_1_min_prices <- do.call(cbind, reg_1_min_prices)
Run Code Online (Sandbox Code Playgroud)

然而,这似乎耗尽了记忆. reg_1_min_prices相互排斥的日子是6,000天1分钟的回报,所以它不是很大.有谁知道怎么解决这个问题?

需要明确的是:reg_1_min_prices包含每天1分钟价格的互斥日,列表中的每个条目都是一个xts对象.

GSe*_*See 12

我使用所提供的战略多米尼克他的回答这个问题

我已经把它变成一个功能,我qmao包.此代码也处于核心getSymbols.FIFinancialInstrument包.

do.call.rbind <- function(lst) {
  while(length(lst) > 1) {
    idxlst <- seq(from=1, to=length(lst), by=2)
    lst <- lapply(idxlst, function(i) {
      if(i==length(lst)) { return(lst[[i]]) }
      return(rbind(lst[[i]], lst[[i+1]]))
    })
  }
  lst[[1]]
}
Run Code Online (Sandbox Code Playgroud)

如果你愿意rbind data.frames,@ JoshuaUlrich 在这里提供了一个优雅的解决方案


据我所知(没有仔细观察),内存不是所提供的三种解决方案中的任何一种(@ JoshuaUlrich,@ Alex's和qmao :: do.call.rbind).所以,它归结为速度......

library(xts)
l <- lapply(Sys.Date()-6000:1, function(x) {
    N=60*8;xts(rnorm(N),as.POSIXct(x)-seq(N*60,1,-60))})
GS <- do.call.rbind
JU <- function(x) Reduce(rbind, x)
Alex <- function(x) do.call(rbind, lapply(x, as.data.frame)) #returns data.frame, not xts

identical(GS(l), JU(l)) #TRUE

library(rbenchmark)
benchmark(GS(l), JU(l), Alex(l), replications=1)
     test replications elapsed relative user.self sys.self user.child sys.child
3 Alex(l)            1  89.575 109.9080    56.584   33.044          0         0
1   GS(l)            1   0.815   1.0000     0.599    0.216          0         0
2   JU(l)            1 209.783 257.4025   143.353   66.555          0         0
Run Code Online (Sandbox Code Playgroud)

do.call.rbind 显然在速度上获胜.


Jos*_*ich 10

您不想使用,merge因为这将返回一个6000列对象,每个列表元素中的每一行都有一行(在我的示例中为2,880,000).而且大部分价值都是NA. cbind.xts只需merge.xts使用一些默认参数值调用,因此您也不想使用它.

我们知道调用rbind.xtsvia 导致的内存问题do.call.Jeff确实拥有更高效的代码,但它是一个不公开的原型.

@ GSee解决方案的替代方案是使用Reduce.这需要一段时间才能在我的笔记本电脑上运行,但即使只有4GB,内存也不是问题.

library(xts)
l <- lapply(Sys.Date()-6000:1, function(x) {
  N=60*8;xts(rnorm(N),as.POSIXct(x)-seq(N*60,1,-60))})
x <- Reduce(rbind, l)
Run Code Online (Sandbox Code Playgroud)