Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using R: How do I create a time-series object with dates?

Tags:

r

time-series

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)
like image 434
Don P Avatar asked Jul 10 '12 21:07

Don P


People also ask

How do you create a time series object in R?

Creating a time seriesThe ts() function will convert a numeric vector into an R time series object. The format is ts(vector, start=, end=, frequency=) where start and end are the times of the first and last observation and frequency is the number of observations per unit time (1=annual, 4=quartly, 12=monthly, etc.).

How does R deal with dates?

Date objects are stored in R as integer values, allowing for dates to be compared and manipulated as you would a numeric vector. Logical comparisons are a simple. When referring to dates, earlier dates are “less than” later dates.


1 Answers

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
like image 142
khoxsey Avatar answered Sep 18 '22 13:09

khoxsey