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

后端 未结 1 752
别那么骄傲
别那么骄傲 2021-02-15 16:13

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

相关标签:
1条回答
  • 2021-02-15 16:34

    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
    
    0 讨论(0)
提交回复
热议问题