9

在一年的时间里,我每小时都会采集一系列值。是否可以创建一个保留小时和年份值的时间序列对象?

我的代码使用股票价格第 1 列中的值,但不使用日期:

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

1 回答 1

23

您没有提供数据样本,但是关于 SO(例如此处)还有很多其他答案涵盖了这个问题。我将 xts 用于我的时间序列工作,尽管还有其他不错的选择。

假设您的数据是两列,您可能通过 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

您可以转换为 xts 时间序列,因此:

> 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
于 2012-07-10T22:59:45.233 回答