Na.locf, but do not trailing NA

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 

Direct na.locf gives 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 can i do 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 do not want the last observation to be carried forward EXCEPT for the very last value not missed. Those. final NAs are not replaced. Many thanks for your help!

+8
r time-series zoo xts
source share
1 answer

Use na.approx from the zoo package (which xts automatically loads):

 na.approx(y, method = "constant", na.rm = FALSE) 
+7
source share

All Articles