计算时间序列中缺失的月份 [英] computing missing months in timeseries
问题描述
我在 R 中有一个包含每月值的数据集.然而,几个月不见了.例如:
I have a dataset in R that contains monthly values. However, some months are missing. For example:
"2001-09-01" "2001-10-01" "2001-12-01" "2002-02-01"
"2001-09-01" "2001-10-01" "2001-12-01" "2002-02-01"
2001 年 11 月缺失,2002 年 1 月缺失.如何将这些月份包含在时间序列中并添加 0 值?
Nov 2001 is missing and Jan 2002 is missing. How do I include those months into the timeseries and add a value of 0 ?
谢谢!
推荐答案
由于这是一个月刊系列,因此将其表示为具有 "yearmon"
课时的系列可能更有意义.前几行设置测试数据,最后两行做实际填充:
Since this is a monthly series it might make sense to represent it as a series with "yearmon"
class times. The first few lines set up the test data and the last two lines do the actual filling:
# set up input data as a zoo series
library(zoo)
d <- c("2001-09-01", "2001-10-01", "2001-12-01", "2002-02-01")
z <- zoo(1:4, as.yearmon(d))
# merge with zero width series
g <- seq(start(z), end(z), 1/12)
zz <- merge(z, zoo(, g), fill = 0)
如果需要 "ts"
系列,则使用 as.ts(zz)
或者如果动物园系列的时间为 "Date"
> 需要类然后尝试: time(zz) <- as.Date(time(zz))
.
If a "ts"
series is desired then use as.ts(zz)
or if a zoo series with times of "Date"
class is wanted then try: time(zz) <- as.Date(time(zz))
.
请注意,通过 R 命令vignette("zoo-faq")
或在网上:
Note that this is also discussed with several examples in FAQ 13 of the zoo FAQ available via the R command vignette("zoo-faq")
or on the net at:
http://cran.r-project.org/web/packages/zoo/vignettes/zoo-faq.pdf
这篇关于计算时间序列中缺失的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!