Using R: How to create a time series object with dates?

I have a series of values ​​taken every hour throughout the year. Is it possible to create a time series object that stores the values ​​of the hour and year?

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

stockprices.ts <- ts(stockprices[,1],start=1, freq=168)
+5
source share
1 answer

You do not provide a sample of your data, but there are many other answers to SO ( here, for example, ) covering this question. I use xts to work with time series, although there are other good options.

Assuming your data is two columns, you might have a data frame loaded through 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 xts to time series in this way:

> 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
+16

All Articles