Reputation: 2949
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?
Upvotes: 1
Views: 1539
Reputation: 10401
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
}
Upvotes: 1