I have a date vector with leading NAs and I'd like to generate an approximate sequence for these NAs using na.approx
from package zoo
.
na.approx
does not work for leading NAs:
x <- as.Date(c(rep(NA,3),"1992-01-16","1992-04-16","1992-07-16",
"1992-10-16","1993-01-15","1993-04-16","1993-07-17"))
as.Date(na.approx(x,na.rm=FALSE))
[1] NA NA NA "1992-01-16" "1992-04-16"
1992-07-16" "1992-10-16" "1993-01-15" "1993-04-16" "1993-07-17"
I thought that I could reverse my vector using rev
but I still get NAs
as.Date(na.approx(rev(x),na.rm=FALSE))
[1] "1993-07-17" "1993-04-16" "1993-01-15" "1992-10-16" "1992-07-16"
"1992-04-16" "1992-01-16" NA NA NA
Any ideas?
Found my answer. na.spline
does a good job with lots of data. In the example above, I have few dates which causes the approximation to drift. However, in my real life example, there is no drift.
as.Date(na.spline(x,na.rm=FALSE))
[1] "1993-07-17" "1993-04-16" "1993-01-15" "1992-10-16" "1992-07-16"
"1992-04-16" "1992-01-16" "1991-10-15" "1991-07-13" "1991-04-06"