分解误差(ts(x [1 [lL:wind],start = start(x),frequency = f),season):在R中

时间:2018-09-06 08:29:07

标签: r time-series lapply holtwinters forecast

我不明白为什么我得到帖子标题中提到的错误。

那我该怎么做。

数据示例

mydat=structure(list(date = structure(c(3L, 2L, 6L, 1L, 7L, 5L, 4L), .Label = c("apr-15", 
"feb-15", "jan-15", "jul15", "jun-15", "march-15", "may-15"), class = "factor"), 
    x1 = c(653411L, 620453L, 742567L, 578548L, 720100L, 553740L, 
    588145L), x2 = c(242108L, 210841L, 255046L, 185243L, 257159L, 
    182594L, 246051L), x3 = c(234394L, 289563L, 341791L, 293608L, 
    306807L, 285190L, 279252L), x4 = c(309228L, 226175L, 292387L, 
    183745L, 223322L, 161218L, 201499L)), .Names = c("date", 
"x1", "x2", "x3", "x4"), class = "data.frame", row.names = c(NA, 
-7L))

mydat<- read.csv("path.csv", sep=";",dec=",")

mydat <- stats::ts(mydat[,-1], frequency = 12, start = c(2015,1))

library("forecast")

    my_forecast <- function(x){
      model <- HoltWinters(x,beta = FALSE, seasonal = "additive")
      fcast <- forecast(model, 5) # 5 month
      return(fcast)
    }

progn=lapply(mydat[1:34], my_forecast)

和错误

 Error in decompose(ts(x[1L:wind], start = start(x), frequency = f), seasonal) : 
  time series has no or less than 2 periods 
5.
stop("time series has no or less than 2 periods") 
4.
decompose(ts(x[1L:wind], start = start(x), frequency = f), seasonal) 
3.
HoltWinters(x, beta = FALSE, seasonal = "additive") 
2.
FUN(X[[i]], ...) 
1.
lapply(d2[1:34], my_forecast) 

如何解决? 主要思想是对所有34个变量进行HoltWinters分析。

1 个答案:

答案 0 :(得分:1)

问题在于lapply函数。 lapply返回一个与X长度相同的列表,其中每个元素都是对X的相应元素应用FUN的结果。您只需运行“ my_forecast”函数即可。

mydat=structure(list(date = structure(c(3L, 2L, 6L, 1L, 7L, 5L, 4L), .Label = c("apr-15", 
    "feb-15", "jan-15", "jul15", "jun-15", "march-15", "may-15"), class = "factor"), 
        x1 = c(653411L, 620453L, 742567L, 578548L, 720100L, 553740L, 
        588145L), x2 = c(242108L, 210841L, 255046L, 185243L, 257159L, 
        182594L, 246051L), x3 = c(234394L, 289563L, 341791L, 293608L, 
        306807L, 285190L, 279252L), x4 = c(309228L, 226175L, 292387L, 
        183745L, 223322L, 161218L, 201499L)), .Names = c("date", 
    "x1", "x2", "x3", "x4"), class = "data.frame", row.names = c(NA, 
    -7L))

mydat<- read.csv("path.csv", sep=";",dec=",")

mydat <- stats::ts(mydat[,-1], frequency = 12, start = c(2015,1))

library("forecast")

my_forecast <- function(x){
   model <- HoltWinters(x,beta = FALSE, seasonal = "additive")
   fcast <- forecast(model, 5) # 5 month
   return(fcast)
}

my_forecast(ts(mydat, start=c(2015,1), end=c(2015,7), frequency=7))