在R开始每日时间序列

max*_*max 13 r time-series

我每天都有关于网站访客数量的时间序列.我的系列从01/06/2014今天开始,14/10/2015所以我希望预测未来的访客人数.如何用R读取我的系列?我在想:

series <- ts(visitors, frequency=365, start=c(2014, 6)) 
Run Code Online (Sandbox Code Playgroud)

如果是的话,在运行我的时间序列模型后,arimadata=auto.arima()我想预测接下来6o天的访客数量,我该怎么做?

h=..?
forecast(arimadata,h=..), 
Run Code Online (Sandbox Code Playgroud)

hshoud 的价值是什么?在此先感谢您的帮助

Rei*_*son 23

ts规范是错误的; 如果您将此设置为每日观察,那么您需要指定2014年的哪一天是6月1日,并在start以下位置指定:

## Create a daily Date object - helps my work on dates
inds <- seq(as.Date("2014-06-01"), as.Date("2015-10-14"), by = "day")

## Create a time series object
set.seed(25)
myts <- ts(rnorm(length(inds)),     # random data
           start = c(2014, as.numeric(format(inds[1], "%j"))),
           frequency = 365)
Run Code Online (Sandbox Code Playgroud)

请注意,我指定startc(2014, as.numeric(format(inds[1], "%j"))).所有复杂的一点都在于解决6月1日的哪一天:

> as.numeric(format(inds[1], "%j"))
[1] 152
Run Code Online (Sandbox Code Playgroud)

一旦你有了这个,你就在那里:

## use auto.arima to choose ARIMA terms
fit <- auto.arima(myts)
## forecast for next 60 time points
fore <- forecast(fit, h = 60)
## plot it
plot(fore)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

鉴于我提供的随机数据,这似乎是合适的...

您需要选择auto.arima()适合您的数据的适当参数.

请注意,x轴标签指的是一年的0.5(一半).

通过动物园这样做

通过zoo使用zoo包创建的对象可能更容易做到:

## create the zoo object as before
set.seed(25)
myzoo <- zoo(rnorm(length(inds)), inds)
Run Code Online (Sandbox Code Playgroud)

请注意,您现在不需要指定任何startfrequency信息; 只需使用inds日常Date对象中的早期计算.

继续像以前一样

## use auto.arima to choose ARIMA terms
fit <- auto.arima(myts)
## forecast for next 60 time points
fore <- forecast(fit, h = 60)
Run Code Online (Sandbox Code Playgroud)

该情节虽然会引起问题,因为x轴是自纪元(1970-01-01)以来的天数,所以我们需要抑制该轴的自动绘图然后绘制我们自己的.这很容易,因为我们有inds

## plot it
plot(fore, xaxt = "n")    # no x-axis 
Axis(inds, side = 1)
Run Code Online (Sandbox Code Playgroud)

这只产生一些标记的刻度; 如果你想要更多控制,告诉R你想要的标记和标签:

## plot it
plot(fore, xaxt = "n")    # no x-axis 
Axis(inds, side = 1,
     at = seq(inds[1], tail(inds, 1) + 60, by = "3 months"),
     format = "%b %Y")
Run Code Online (Sandbox Code Playgroud)

这里我们每3个月绘制一次.


小智 9

时间序列对象不适用于创建每日时间序列。我会建议你使用zoo图书馆。

library(zoo)
zoo(visitors, seq(from = as.Date("2014-06-01"), to = as.Date("2015-10-14"), by = 1))
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提供清晰的样本。现在为了进一步扩展这个答案,您可以将“zoo”系列视为常规时间序列,例如:plot(myzoo),或##使用auto.arima来选择ARIMA术语fit &lt;- auto.arima(myzoo) ## 对接下来 60 个时间点的预测 &lt;- Forecast(fit, h = 60) (2认同)