从数据框创建ts并使用STL进行分解

时间:2017-07-25 09:03:10

标签: r stl time-series

我是R的新手,正在创建我的第一次系列分析。 我的第一步是将数据(数据框)转换为时间序列,并且:

这是转化前的数据:

           Date    Value Season
1576 2017-01-30 45330.34      0
1604 2017-02-27 43757.68      0
1693 2017-03-30 50092.90      1
1723 2017-04-29 39405.65      0
1812 2017-05-30 42031.80      0
1842 2017-06-29 40008.67      0

格式为:

> str(mth3)
'data.frame':   66 obs. of  3 variables:
 $ Date   : Date, format: "2012-01-30" "2012-02-28" ...
 $ Value  : num  40222 43437 46047 33813 35757 ...
 $ Season : int  0 0 1 1 0 0 0 0 0 2 ...

使用此代码转换数据时:

mth4 <- ts(mth3, frequency=12, start=c(2012,1), end=c(2017,6)) 

然后数据如下:

          Date  Value        Season
Jan 2017 17196 45330.34      0
Feb 2017 17224 43757.68      0
Mar 2017 17255 50092.90      1
Apr 2017 17285 39405.65      0
May 2017 17316 42031.80      0
Jun 2017 17346 40008.67      0

mth4中的数据格式为:

-Series [1:66, 1:3] from 2012 to 2017: 15369 15398 15429 15459 15490 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:3] "Date" "Value" "Season"

将数据分解为趋势,季节性和随机行为

mth_stl <- stl(mth4, s.window="periodic")

此错误的结果是:

only univariate series are allowed

我的猜测是我在格式化方面做错了,但我不知道为什么并且花了相当多的时间来搜索这个论坛。

1 个答案:

答案 0 :(得分:0)

尽管评论和我对包的亲和力,你不需要xts。 :)

问题在于错误消息,“只允许单变量系列”。您的mth4对象是多变量时间序列。 stl()仅接受单变量系列,因此您需要提取Value列以传递给stl()

R> mth_stl <- stl(mth4[,"Value"], s.window="periodic")
R> str(mth_stl)
List of 8
 $ time.series: Time-Series [1:66, 1:3] from 2012 to 2017: 621 175 425 -104 2528 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:3] "seasonal" "trend" "remainder"
 $ weights    : num [1:66] 1 1 1 1 1 1 1 1 1 1 ...
 $ call       : language stl(x = mth4[, "Value"], s.window = "periodic")
 $ win        : Named num [1:3] 661 19 13
  ..- attr(*, "names")= chr [1:3] "s" "t" "l"
 $ deg        : Named int [1:3] 0 1 1
  ..- attr(*, "names")= chr [1:3] "s" "t" "l"
 $ jump       : Named num [1:3] 67 2 2
  ..- attr(*, "names")= chr [1:3] "s" "t" "l"
 $ inner      : int 2
 $ outer      : int 0
 - attr(*, "class")= chr "stl"

您也无需在Date对象中包含data.frame中的ts列。 ts个对象具有基于其startendfrequency组件的隐含日期。因此,您可以使用:

创建ts对象
mth4 <- ts(mth3[, c("Value", "Season")], frequency=12, start=c(2012,1), end=c(2017,6))