9
votes

I have a series of values taken every hour over a year. Is it possible to create a time-series object that retains the hour and year values?

My code uses the values in column 1 of stockprices, but does not use the date:

stockprices.ts <- ts(stockprices[,1],start=1, freq=168)
1

1 Answers

23
votes

You don't provide a sample of your data, but there are a lot of other answers on SO (here for example) covering this question. I use xts for my time series work, although there are other good choices.

Assuming your data is two columns, you might have a data frame loaded via read.table:

> stockprices <- data.frame(prices=c(1.1,2.2,3.3),
               timestamps=c('2011-01-05 11:00','2011-01-05 12:00','2011-01-05 13:00'))
> stockprices
  prices       timestamps
1    1.1 2011-01-05 11:00
2    2.2 2011-01-05 12:00
3    3.3 2011-01-05 13:00

You can convert to xts time series thus:

> require(xts)
> stockprices.ts <- xts(stockprices$prices, order.by=as.POSIXct(stockprices$timestamps))
> stockprices.ts
                    [,1]
2011-01-05 11:00:00  1.1
2011-01-05 12:00:00  2.2
2011-01-05 13:00:00  3.3