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)
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.).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With