Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Filling missing dates in a time series?

I have a zoo time series with missing days. In order to fill it and have a continuous series I do...

I generate a chron date-time sequence from start to end.

I merge my series with this one.

I use na.locf to substitute NAs with las obsservation.

I remove the syntetic chron sequence.

Can I do same easier? Maybe with some index function related to the frequency?

like image 300
skan Avatar asked Aug 24 '10 10:08

skan


People also ask

How do I change the date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.


2 Answers

It's slightly easier if you use a "empty" zoo object with an index.

> x <- zoo(1:10,Sys.Date()-10:1)[c(1,3,5,7,10)]
> empty <- zoo(order.by=seq.Date(head(index(x),1),tail(index(x),1),by="days"))
> na.locf(merge(x,empty))
2010-08-14 2010-08-15 2010-08-16 2010-08-17 2010-08-18 
         1          1          3          3          5 
2010-08-19 2010-08-20 2010-08-21 2010-08-22 2010-08-23 
         5          7          7          7         10 

EDIT: For intra-day data (using Gabor's excellent xout= suggestion):

> index(x) <- as.POSIXct(index(x))
> na.locf(x, xout=seq(head(index(x),1),tail(index(x),1),by="15 min"))
like image 139
Joshua Ulrich Avatar answered Sep 24 '22 21:09

Joshua Ulrich


This is covered in question 13 of the zoo FAQ http://cran.r-project.org/web/packages/zoo/vignettes/zoo-faq.pdf which uses the xout= argument of na.locf to eliminate the merge step. Be sure you are using zoo 1.6.4 or later since this feature was added recently.

like image 29
G. Grothendieck Avatar answered Sep 23 '22 21:09

G. Grothendieck