我可以在 R 中指定时间序列的日期和时间吗?

Can I specify the dates and times of a time series in R?

我有一个数据集,第一列包含时间和日期,第二列包含股票价格。

我使用了以下格式。

      Time              Price
2015-02-01 10:00         50

我想把它变成一个时间序列对象。我尝试了 ts(data) 函数,但是当我绘制数据时,我无法观察到 x 轴上的日期。我也试过 ts(data, start=) 函数。因为我有一些时间缺少价格,而且这些时间不包括在我的数据集中,所以如果我设置开始日期和频率,我的图就会产生误导。

这是我的示例数据。它被称为 df.

           time         price    

1   2013-05-01 00:00:00 124.30
2   2013-05-01 01:00:00 98.99
3   2013-05-01 02:00:00 64.00
4   2013-05-01 03:00:00 64.00

这是我使用的代码

Time1 <- ts(df) 
autoplot(Time1)

也试过了,

Time1 <- zoo(Time_series_data[,2], order.by = Time_series_data[,1])
Time_n <- ts(Time1)
autoplot(Time1)

但是,当我使用 autoplot(Time1) 绘制图表时,x 轴不显示我指定的时间,而是显示从 0 到 4 的数字。我想要一个包含日期的 ts 对象的绘图x 轴中的列和 Y 中的值

有什么方法可以将其转换为 R 中的时间序列对象。谢谢。

尝试以下操作:

使用 tibble 包中的漂亮 tribble 函数创建一些数据。

library(tibble)
df <- tribble(~time,      ~price,
   "2013-05-01 00:00:00", 124.30,
   "2013-05-01 01:00:00", 98.99,
   "2013-05-01 02:00:00", 64.00,
   "2013-05-01 03:00:00", 64.00)

time列是一个字符class,不能用通常的方式绘制。所以使用 as.Posixct 转换它。我将在这里使用 dplyr 包,但这是可选的。

library(dplyr)

df <- df %>%
  mutate(time=as.POSIXct(time))

接下来,将数据转换为时间序列对象。这需要 xts 包,尽管我确信还有其他选项,包括 zoo

library(xts)
df.ts <- xts(df[, -1], order.by=df$time)

现在您可以可视化数据了。

plot(df.ts)  # This should call the `plot.xts` method

如果你喜欢 ggplot2.

library(ggplot2)
autoplot(df.ts)