8

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!

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
R novice
  • 83
  • 3

1 Answers1

7

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

na.approx(y, method = "constant", na.rm = FALSE)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341