R:带有 NA 数据的 ts()

R: ts() with NA data

我有以下功能:

ts.dat <- ts(data=dat$sales, start = 1, frequency = 12)

TS。数据 returns

   Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
1 9000 8600 8500 8600 8500 8300 8600 9100 8800 8700 9300 7900
2 7900 8800 8500 8900 9000 8800 8800 9100 9500 8900 9200 8400
3 8400 9200 9500 9100 8700 8300   NA

然而,

 plot(stl(ts.dat, s.window=12))

returns

Error in na.fail.default(as.ts(x)) : missing values in object'plot':

我试过na.action=na.pass,但没用。如果这是原因,知道如何处理 NA 吗?

另外:是否有机会以 dat 的第一次约会作为开始?

Any idea how to deal with the NA, if that is the reason?

您需要使用na.action = na.omit,即计算时去掉NA

plot(stl(ts.dat, s.window=12, na.action = na.omit))

na.pass 将简单地假定 NA 为正常观察。但是还是会报错,因为stl()后面调用编译后的代码,无法识别NA.

Any chance to take the first date from dat as the start?

看看?ts底部的例子:

 ## Using July 1954 as start date:
 gnp <- ts(cumsum(1 + round(rnorm(100), 2)),
           start = c(1954, 7), frequency = 12)

从 1954 年 7 月开始,输入 start = c(1954, 7)

您还可以估算时间序列中缺失的数据。 (用合理的值替换NA)

有 R 包可以做到这一点(例如 imputeTSzoo)。

特别是 imputeTS 有一些函数是用季节性替换时间序列中缺失数据的非常好的选择。 (na_seadec() 或 na_kalman()) (它还有其他插补函数 - 这里是 overview

此处的解决方案如下所示:

library(imputeTS)
x <- na_seadec(ts.dat)
plot(stl(x, s.window=12))