Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-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!

like image 792
R novice Avatar asked Sep 03 '11 22:09

R novice


1 Answers

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

na.approx(y, method = "constant", na.rm = FALSE)
like image 70
G. Grothendieck Avatar answered Nov 16 '22 09:11

G. Grothendieck