我想将时间序列与其移动平均线一起绘制,如a Forecasting: Principles and Practices中的示例,我使用自己的时间序列salests
:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2015 110 115 92 120 125 103 132 136 114 139 143 119
2016 150 156 130 169 166 142 170 173 151 180 184 163
然后我使用与书中类似的代码:
autoplot(salests, series="Sales") +
forecast::autolayer(ma(salests, 5), series="5 Moving Average")
但我收到错误:
Error: Invalid input: date_trans works with objects of class Date only
我做错了什么?我似乎只是在关注这本书。
提前致谢
答案 0 :(得分:2)
以下是一些可以帮助您的想法。
# I start reading your dataset
df1 <- read.table(text='
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2015 110 115 92 120 125 103 132 136 114 139 143 119
2016 150 156 130 169 166 142 170 173 151 180 184 163
', header=T)
# Set locale to 'English' if you have a different setting
Sys.setlocale( locale='English' )
# I reshape your dataset in long format
library(reshape)
df2 <- melt(df1)
df2$time <- paste0("01-",df2$variable,'-',rep(rownames(df1), ncol(df1)))
df2$time <- as.Date(df2$time, "%d-%b-%Y")
( df2 <- df2[order(df2$time),] )
# variable value time
# 1 Jan 110 2015-01-01
# 3 Feb 115 2015-02-01
# 5 Mar 92 2015-03-01
# 7 Apr 120 2015-04-01
# 9 May 125 2015-05-01
# 11 Jun 103 2015-06-01
# 13 Jul 132 2015-07-01
# 15 Aug 136 2015-08-01
# 17 Sep 114 2015-09-01
# 19 Oct 139 2015-10-01
# 21 Nov 143 2015-11-01
# 23 Dec 119 2015-12-01
# 2 Jan 150 2016-01-01
# 4 Feb 156 2016-02-01
# 6 Mar 130 2016-03-01
# 8 Apr 169 2016-04-01
# 10 May 166 2016-05-01
# 12 Jun 142 2016-06-01
# 14 Jul 170 2016-07-01
# 16 Aug 173 2016-08-01
# 18 Sep 151 2016-09-01
# 20 Oct 180 2016-10-01
# 22 Nov 184 2016-11-01
# 24 Dec 163 2016-12-01
现在创建一个时间序列ts
对象
( salests <- ts(df2$value, frequency=12, start = c(2015,1)) )
# Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
# 1 110 115 92 120 125 103 132 136 114 139 143 119
# 2 150 156 130 169 166 142 170 173 151 180 184 163
并绘制它:
library(ggfortify)
library(forecast)
autoplot(salests) +
forecast::autolayer(ma(salests, 5), series="5 Moving Average")