当 2 年多月的数据缺失时,如何在 ts() 函数中填写日期?

How do I fill in Dates in ts() function, when there is missing data for many months for over 2 years?

这是数据:

e <- data.frame( date = c("2016-03-08", "2016-05-19" ,"2016-05-19" ,"2016-09-02" ,"2016-09-02", "2016-11-23", "2016-12-29","2017-02-08" ,"2017-07-24", "2017-07-26" ,"2018-04-05" ,"2018-06-01", "2019-02-07" ,"2019-03-25"), price = c(1300, 1300, 1300 ,1300 ,1300 ,1300 ,1300 ,1300 ,1300 ,1300 ,1375 ,1375 ,1405 ,1405))

summary(e)

当我使用 ts() 时,我不确定为什么值会发生变化。有人可以解释一下吗?

b <- ts(e$price, start = c(2016,3), end = c(2019,3), frequency = 12)

输出:2013 年 3 月 的正确价格是 1300,但 2019 年 3 月有错误的值,它有 1300 而不是 1405

如何解决这个问题?

您的数据不代表时间序列,因为从数学上讲,时间序列是从唯一时间到值的函数。另外 ts 不能很好地处理日常数据。

如果我们省略任何 year/month 中除最后一个数据点之外的所有数据点,那么我们可以通过将其读入动物园系列并将日期列转换为每月 ts 系列到 yearmon class 并使用最后一个值聚合相同的 year/months。然后将其转换为 ts class.

library(zoo)

z <- read.zoo(e, FUN = as.yearmon, aggregate = function(x) tail(x, 1))
as.ts(z)

给予:

      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
2016           1300   NA 1300   NA   NA   NA 1300   NA 1300 1300
2017   NA 1300   NA   NA   NA   NA 1300   NA   NA   NA   NA   NA
2018   NA   NA   NA 1375   NA 1375   NA   NA   NA   NA   NA   NA
2019   NA 1405 1405