简体   繁体   English

在 R 中循环时间序列对象

[英]Loop over time-series object in R

I have a time-series object as:我有一个时间序列对象:

 seq <- seq(as.POSIXct("2015-09-01"),as.POSIXct("2015-09-02"), by = "120 mins")
 ob <- xts(rnorm(length(seq)),seq) # xts object

One important property of ob is that it gets updated in real-time, ie, new observation get appended to it by using rbind . ob一个重要特性是它会实时更新,即使用rbind将新的观察结果附加到它上面。 Therefore, I don't know the exact length of this object.因此,我不知道这个对象的确切长度。 Now, I want to read the ob row by row and perform my required operation.现在,我想逐行读取ob并执行我需要的操作。 Let us assume that I will read the row of ob and then add this row to another static time-series ( xts ) object.让我们假设我将读取ob行,然后将此行添加到另一个静态时间序列 ( xts ) 对象。 How should I read the ob row by row?我应该如何逐行阅读ob Till now, I approached it as直到现在,我接近它

  i <- 1
  l <- ob[i,]
  while(NROW(l)) # Check I have a row to read
  {   
      print(l) # dummy operation
      i <- i+1
      l <- ob[i,] 
  }

This code does its job, but it results in error as这段代码完成了它的工作,但它会导致错误

Error in `[.xts`(ob, i, ) : subscript out of bounds

I understand the error.我理解错误。 I want to know, is there a better way to read xts objects row by row?我想知道,有没有更好的方法来逐行读取xts对象?

Would this do what you want?这会做你想要的吗?

library(xts)

seq <- seq(as.POSIXct("2015-09-01"),as.POSIXct("2015-09-02"), by = "120 mins")
ob <- xts(rnorm(length(seq)),seq) # xts object

i <- 1
l <- ob[i,]
while(NROW(l))
{
    print(l)
    i <- i+1
    l <- try(ob[i,], silent=TRUE)
    if(class(l)[1]=="try-error") break
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM