代码之家  ›  专栏  ›  技术社区  ›  ClimateUnboxed

季节循环分析中NA的处理

  •  6
  • ClimateUnboxed  · 技术社区  · 7 年前

    我有一个时间序列的每月数据与许多缺失的数据点,设置为NA。我只想从数据中减去年度周期,忽略缺失的条目。分解函数似乎不能处理丢失的数据点,但我在其他地方看到建议使用季节性包。不过,我也遇到了问题,在那里也与娜。

    下面是使用内置数据集的问题的最小可再现性示例。。。

    library(seasonal)
    
    # set range to missing NA in Co2 dataset
    c2<-co2
    c2[c2>330 & c2<350]=NA
    seas(c2,na.action=na.omit)
    
    Error in na.omit.ts(x) : time series contains internal NAs
    

    是的,我知道!所以我让你把它们删掉!让我们试试这个:

    seas(c2,na.action=na.x13)
    
    Error: X-13 run failed
    
    Errors:
    - Adding MV1981.Apr exceeds the number of regression effects
      allowed in the model (80).
    

    嗯,有意思,不知道这意味着什么,好吧,请排除NA:

    seas(c2,na.action=na.exclude)
    
    Error in na.omit.ts(x) : time series contains internal NAs
    

    那没什么用!为了更好的衡量

    decompose(c2)
    
    Error in na.omit.ts(x) : time series contains internal NAs
    

    R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
    Copyright (C) 2018 The R Foundation for Statistical Computing
    Platform: x86_64-pc-linux-gnu (64-bit)
    

    为什么把娜排除在外会有这样的问题?我显然是完全愚蠢,但我看不出我对seas函数有什么错。很高兴考虑使用xts的替代解决方案。

    1 回复  |  直到 7 年前
        1
  •  5
  •   ClimateUnboxed    7 年前

    我的第一个解决方案,简单地手动计算季节周期,转换成数据帧减去向量,然后转换回来。

    # seasonal cycle
    scycle=tapply(c2,cycle(c2),mean,na.rm=T) 
    # converting to df
    df=tapply(c2, list(year=floor(time(c2)), month = cycle(c2)), c)
    # subtract seasonal cycle
    for (i in 1:nrow(df)){df[i,]=df[i,]-scycle}
    # convert back to timeseries
    anomco2=ts(c(t(df)),start=start(c2),freq=12)
    

    不太漂亮,效率也不高。

    误用的评论使我想到另一个问题 Seasonal decompose of monthly data including NA in r

    library(zoo)
    c2=co2
    c2[c2>330&c2<350]=NA
    d=decompose(na.StructTS(c2)) 
    plot(co2)
    lines(d$x,col="red")
    

    结果表明,通过缺失周期可以很好地重建序列。

    black lines shows Co2 series with missing chunk and the red line is the reconstructed series

    解构的输出具有趋势性和季节性。我希望我能把我的赏金转给用户 https://stackoverflow.com/users/516548/g-grothendieck

    然而,如果缺失的部分在系列的末尾,软件就必须推断出趋势,并且有更多的困难。原始序列(黑色)保持趋势,而重建序列(红色)的趋势较小:

    c2=co2
    c2[c2>350]=NA
    d=decompose(na.StructTS(c2)) 
    plot(co2)
    lines(d$x,col="red")
    

    extrapolation of data using zoo

    最后,如果缺少的部分是在系列的开始,软件就无法在时间上向后推断,并抛出一个错误。。。我觉得另一个问题来了。。。

    c2=co2
    c2[c2<330]=NA
    d=decompose(na.StructTS(c2)) 
    
    Error in StructTS(y) :  
    the first value of the time series must not be missing
    
        2
  •  2
  •   Steffen Moritz    7 年前

    (例如来自包装输入或动物园)

    例如,插补具有季节性时间序列的额外插补算法,例如:

    x <- na.seadec(co2)
    

    x <- na.kalman(co2)
    

    现在继续,不要丢失数据。

    Adrian Tompkins的一个重要提示(另请参见下面的评论): 当丢失的数据在中间的某个地方时,这将是最好的。对于许多领先的NAs来说,这种方法不是一个好的选择。在这种情况下,它填充了NAs,但无法向后推断趋势:

    c2<-co2
    c2[c2<330]<-NA
    c3<-na.kalman(c2)
    c4<-na.seadec(c2)
    plot(co2)
    lines(c3,col="blue")
    lines(c4,col="red")
    

    enter image description here