na.locf but don't do trailing NAs
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-0开发者_如何学C9-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!
Use na.approx
from the zoo package (which is automatically loaded by xts):
na.approx(y, method = "constant", na.rm = FALSE)
精彩评论