na.locf但不做尾随的NA

时间:2011-09-03 22:21:26

标签: r time-series xts zoo

我有以下时间序列

> y<- xts(1:10, Sys.Date()+1:10)
> y[c(1,2,5,9,10)] <- NA
> y
           [,1]
2011-09-04   NA
2011-09-05   NA
2011-09-06    3
2011-09-07    4
2011-09-08   NA
2011-09-09    6
2011-09-10    7
2011-09-11    8
2011-09-12   NA
2011-09-13   NA

直接的na.locf给我这个:

> na.locf(y)
           [,1]
2011-09-04   NA
2011-09-05   NA
2011-09-06    3
2011-09-07    4
2011-09-08    4
2011-09-09    6
2011-09-10    7
2011-09-11    8
2011-09-12    8
2011-09-13    8

我怎么做到这一点?

           [,1]
2011-09-04   NA
2011-09-05   NA
2011-09-06    3
2011-09-07    4
2011-09-08    4
2011-09-09    6
2011-09-10    7
2011-09-11    8
2011-09-12    NA
2011-09-13    NA

我不希望最后一次观察结果除了最后一次非缺失值之外,即不会替换尾随的NA。非常感谢你的帮助!

1 个答案:

答案 0 :(得分:7)

使用zoo包中的na.approx(由xts自动加载):

na.approx(y, method = "constant", na.rm = FALSE)