【问题标题】:R ts object - Preserve index while removing NAsR ts 对象 - 删除 NA 时保留索引
【发布时间】:2016-11-11 09:23:43
【问题描述】:

考虑一个具有多个NA 值的时间序列对象:

x <- seq(10)
x[seq(2,10,2)] <- NA
x <- ts(x)

这是默认索引:

index(x)
[1]  1  2  3  4  5  6  7  8  9 10

如果我使用 na.exclude 删除 NA 值,我会得到一个新索引:

na.exclude(x)
[1] 1 3 5 7 9
attr(,"na.action")
[1]  2  4  6  8 10
attr(,"class")
[1] "exclude"    
index(na.exclude(x))
[1] 1 2 3 4 5

如果我尝试na.omit,我只会得到一个错误:

na.omit(x)
Error in na.omit.ts(x) : time series contains internal NAs
> index(na.omit(x))
Error in na.omit.ts(x) : time series contains internal NAs

如果我尝试将index 设置为我需要的值(我希望这应该是删除NAs 的自然结果),我会收到另一个错误:

index(x) <- c(1,3,5,7,9)
Error in UseMethod("index<-") : no applicable method for 'index<-' 
applied to an object of class "ts"

有没有直接的方法来删除NA 值,同时保留非NAs 的原始索引?我宁愿不使用xts, zoo 等,因为包stats 中有一些函数只接受ts 对象。

谢谢。

【问题讨论】:

    标签: r statistics time-series


    【解决方案1】:

    您可以使用 tseries 包中的 na.remove 执行此操作(这也将保留 ts 类):

    x <- seq(10)
    x[seq(2,10,2)] <- NA
    x <- ts(x)
    

    然后:

    library(tseries)
    na.remove(x)
    #Time Series:
    #Start = 1 
    #End = 9 
    #Frequency = 0.5 
    #[1] 1 3 5 7 9
    #attr(,"na.removed")
    #[1]  2  4  6  8 10
    
    index(na.remove(x))
    #[1] 1 3 5 7 9
    

    ts 类保持原样:

    class(x)
    #[1] "ts"
    class(na.remove(x))
    #[1] "ts"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      相关资源
      最近更新 更多