【问题标题】:R: autolayer moving average gives errorR:自动层移动平均给出错误
【发布时间】:2017-10-29 09:10:32
【问题描述】:

我想绘制一个时间序列及其移动平均线,就像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

我做错了什么?看来我只是在追书。

提前致谢

【问题讨论】:

    标签: r ggplot2 forecasting


    【解决方案1】:

    这里有一些可以帮助你的想法。

    # 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")
    

    【讨论】:

    • 我认为诀窍(至少对我而言,并且我从您的帖子中得出的结论-谢谢!)是分离 ggfortify 和预测,然后重新连接,确保在预测之前附加 ggfortify。虽然不需要从我用于生存图的预测包中打印对象
    • @user1420372 感谢您的建议!
    猜你喜欢
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2013-12-22
    • 2018-10-21
    • 2023-03-12
    • 2016-05-16
    • 2020-02-04
    • 2017-10-27
    相关资源
    最近更新 更多