简体   繁体   中英

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 . 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. Let us assume that I will read the row of ob and then add this row to another static time-series ( xts ) object. How should I read the ob row by row? 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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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