r语言 - 从 "ts" 对象中删除 NA 以使 acf() 和 pacf() 工作



如何从此时间序列中删除NA?

x <- structure(c(NA, 15.3471263711111, 23.7495828967391, 17.6522039782609, 
13.950342245, 18.6679701043956, 21.7398276684783, 22.4975495326087, 
17.1164915533333, 17.7142983241758, 20.5018974402174, 20.841587, 
18.9183467888889, 15.4600196181319, 17.8721988695652, 20.0170066630435, 
18.5086658241758, 15.5306393346154, 16.0669595836957, 20.2165807554348, 
16.25535685, 14.8567082505495, 15.2826896483696, 12.1608449365543, 
8.88960227944444, 16.1804220681319, 19.7431830652174, 15.0564858630435, 
15.1309696333333, 15.9665181153846, 17.7906991630435, 18.3519159722826, 
15.7932861428571, 11.9033367478022, 16.378045125, 16.4570617070652, 
11.8673526106667, 17.0768826978022, 17.6064028967391, 18.8143230434783, 
15.1196432378882, NA, NA, NA), .Tsp = c(2004, 2014.75, 4), class = "ts")
#          Qtr1      Qtr2      Qtr3      Qtr4
#2004        NA 15.347126 23.749583 17.652204
#2005 13.950342 18.667970 21.739828 22.497550
#2006 17.116492 17.714298 20.501897 20.841587
#2007 18.918347 15.460020 17.872199 20.017007
#2008 18.508666 15.530639 16.066960 20.216581
#2009 16.255357 14.856708 15.282690 12.160845
#2010  8.889602 16.180422 19.743183 15.056486
#2011 15.130970 15.966518 17.790699 18.351916
#2012 15.793286 11.903337 16.378045 16.457062
#2013 11.867353 17.076883 17.606403 18.814323
#2014 15.119643        NA        NA        NA

这给我带来了麻烦:

acf(x)
#Error in na.fail.default(as.ts(x)) : missing values in object
pacf(x)
#Error in na.fail.default(as.ts(x)) : missing values in object

使用window选择非NA段:

xx <- window(x, start = c(2004, 2), end = c(2014, 1))
acf(xx)
pacf(xx)

或者保留这些NA,但使用:

acf(x, na.action = na.pass)
pacf(x, na.action = na.pass)

x是ts对象,而不是数据帧。

class(x)
## [1] "ts"

要消除前导和尾随NA,假设没有其他NA,请使用na.omit,如下所示:

na.omit(x)

备注

如果存在内部NA,即不领先或落后的NA,则使用其中一个,所有这些NA都去除了领先和落后的NA加上所描述的动作

library(zoo)
xx <- replace(x, 10, NA) # add an internal NA
na.trim(xx)    # preserve internal NA's
na.approx(xx)  # fill in internal NA's using linear interpolation
na.spline.ts <- function(x, ...) as.ts(na.spline(as.zoo(x), ...))
na.spline(na.trim(xx))  # spline interpolation

最新更新