在 R 中扩展动物园时间线 [英] expand zoo timeline in R

查看:30
本文介绍了在 R 中扩展动物园时间线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间序列数据集,其中包含 8 月和 9 月的一些数据点.

Hi I have a time series dataset contains a few data points in Aug and Sep.

如何轻松地用默认值填充缺失的天数,在本例中为 0:

How can I fill in the missing days with a default value easily, say 0 in this case:

我现在的想法是merge数据集与我喜欢的时间线的顺序时间序列,然后执行na.fill以使用默认值替换NAs我想要.

What I am thinking right now to merge the dataset with a sequential time series for the timeline I like, then do na.fill to replace NAs with the default value I want.

这就是我所做的:

# This is my data z1
z1 <- zoo(c(1,2,3,4,5), as.Date(c('2013-08-09', '2013-08-12', '2013-09-02', '2013-09-09', '2013-09-15')))

# This is the timeline I want
z2 <- zoo(0, seq(from=as.Date('2013-08-01'), to=as.Date('2013-09-30'), by="day")) 

# This is my result
na.fill(merge(z1, z2)[,1], 0)

但我想知道是否已经存在一个功能来执行我想要的操作.类似的东西:

But I am wondering is there a function already existing to do what I want. Something like:

result <- foo_fill(z1, 0, start, end)

推荐答案

如果你想用固定的指定值替换 NA,我认为 merge 是要走的路.不过,您可以进行一些简化:您不需要 z2 中的零列",并且您可以在 merge 步骤中填充零:

If you want to replace NAs with fixed specified values, I think merge is the way to go. You can make some simplifications though: you don't need the 'zero-column' in z2, and you can fill with zeros in the merge step:

# input as per question
z1 <- zoo(c(1,2,3,4,5), 
        as.Date(c('2013-08-09', '2013-08-12', '2013-09-02', '2013-09-09', '2013-09-15')))
start <- as.Date('2013-08-01')
end <- as.Date('2013-09-30')

tt <- seq(start, end, by = "day")
merge(z1, zoo(, tt), fill = 0)

另一方面,如果你想用最后一个非 NA (na.locf) 替换 NA,那么 xout 参数可能是一种方法指定用于额外和插值的日期范围,并且您不需要 merge.例如:

On the other hand, if you want to replace NAs by the last previous non-NA (na.locf), then the xout argument may be a way to specify which date range to use for extra- and interpolation, and you don't need merge. For example:

na.locf(z1, xout = tt)

这篇关于在 R 中扩展动物园时间线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆