na.locf but don't do trailing NAs

假装没事ソ 提交于 2019-12-30 08:23:57

问题


I have the following time series

> 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

A straight na.locf give me this:

> 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

how do i get to this?

           [,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

I dont want last observation to be carried forward EXCEPT for the very last non-missing value.. i.e. the trailing NAs are NOT replaced. Thanks so much for your help!


回答1:


Use na.approx from the zoo package (which is automatically loaded by xts):

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


来源:https://stackoverflow.com/questions/7296204/na-locf-but-dont-do-trailing-nas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!