1
votes

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, i.e., 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?

1
I'd try to vectorize that operation to avoid the loop. But to answer your question, I think you want to use the length of ob[, 1] or rather nrow(ob) in each iteration -- as the length of what you are currently checking will be always one (column), so not respecting the last row and trying to read infinitive number of records.daroczig
I got your point and I have changed length to NROW, but still it is not solving the issue fully.Haroon Rashid
Maybe just encapsulate your last assignment in a try()?Dominic Comtois

1 Answers

1
votes

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
}