且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R:填写时间序列中缺少的日期?

更新时间:2023-02-26 19:55:06

如果使用带有索引的空" zoo对象,则会稍微容易一些.

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 

对于日内数据(使用Gabor出色的xout=建议):

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"))