【问题标题】:How to convert stl output to dataframe but keep time series time step?如何将 stl 输出转换为数据帧但保持时间序列时间步长?
【发布时间】:2018-10-21 22:16:22
【问题描述】:

我有时间序列数据,我使用 stl() 命令从数据中提取季节性。现在,我想将趋势数据用于其他一些分析,但在将 stl 输出转换为数据帧时遇到了问题。

我试过了:

KK.DF <- as.data.frame(KK14stl$time.series)

但这忽略了数据的日期间隔,因为在某些情况下这是超过 40 年的月度数据。

我也试过了:

KK.DF.V2 <-as.data.frame(as.xts(KK14stl$time.series))

但是使用嵌套在列号列中的每月日期创建一个数据框,现在确定如何从无名列中提取它。当我这样做时它不会出现

names(KK.DF.V2)

关于如何获取包含日期和时间序列数据的数据框有什么建议吗?

【问题讨论】:

  • 试试KK14stl$trend。但是我经常在这个东西里面得到NAs,所以很难添加。此外,如果您不添加一些示例数据,我将无能为力。

标签: r time-series


【解决方案1】:

只有当你通过print.ts方法观察到ts对象时才会计算出来,不会存储在对象中。您可以搜索print.ts 获取考虑到各种细微差别和频率类型的代码。

如果您只是想快速修复每月数据,您可以使用以下方法:

s <- stl(nottem,"per")
s.DF <- as.data.frame(s$time.series)
rownames(s.DF) <- paste(month.abb[cycle(s$time.series)], floor(time(s$time.series)))

head(s.DF)
          seasonal    trend remainder
Jan 1920 -9.347198 49.68067 0.2665254
Feb 1920 -9.855250 49.54552 1.1097288
Mar 1920 -6.853301 49.41037 1.8429318
Apr 1920 -2.763471 49.32862 0.1348488
May 1920  3.501357 49.24688 1.3517676
Jun 1920  8.983303 49.21027 0.3064259

【讨论】:

    【解决方案2】:

    stl的输出是这样的:

                seasonal    trend     remainder
    Jan 1975  0.045860672 7.606192 -1.2870523041
    Feb 1975 -0.165838793 7.557013 -1.0261737394
    Mar 1975  0.182449236 7.507833  0.8597173305
    

    使用 as.data.frame 会产生以下结果:

    KK.DF <- as.data.frame(KK14stl$time.series)
    
           seasonal    trend     remainder
    1    0.045860672 7.606192 -1.2870523041
    2   -0.165838793 7.557013 -1.0261737394
    3    0.182449236 7.507833  0.8597173305
    4    0.023504974 7.457380  1.0691145599
    5   -0.006006918 7.406927  1.1490794183
    6   -0.046599828 7.366488  1.2301122554
    
    names(KK.DF)
    "seasonal"  "trend"     "remainder"
    

    使用 as.xts 会产生以下结果:

    KK.DF.V2 <-as.data.frame(as.xts(KK14stl$time.series))
    
                seasonal    trend     remainder
    Jan 1975  0.045860672 7.606192 -1.2870523041
    Feb 1975 -0.165838793 7.557013 -1.0261737394
    Mar 1975  0.182449236 7.507833  0.8597173305
    Apr 1975  0.023504974 7.457380  1.0691145599
    May 1975 -0.006006918 7.406927  1.1490794183
    Jun 1975 -0.046599828 7.366488  1.2301122554
    
    names(KK.DF.V2)
    "seasonal"  "trend"     "remainder"
    

    KK.DF.V2 数据框有时间步长,但在我无法调用的未命名列中。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2020-03-14
      相关资源
      最近更新 更多