【发布时间】:2016-03-28 13:29:34
【问题描述】:
我正在使用具有每小时数据的时间序列数据集。数据包含一些缺失值,因此我尝试创建具有正确时间值的数据帧 (time_seq) 并与原始数据进行合并,以便缺失值变为“NA”。
> data
date value
7980 2015-03-30 20:00:00 78389
7981 2015-03-30 21:00:00 72622
7982 2015-03-30 22:00:00 65240
7983 2015-03-30 23:00:00 47795
7984 2015-03-31 08:00:00 37455
7985 2015-03-31 09:00:00 70695
7986 2015-03-31 10:00:00 68444
//converting the date in the data to POSIXct format.
> data$date <- format.POSIXct(data$date,'%Y-%m-%d %H:%M:%S')
// creating a dataframe with the correct sequence of dates.
> time_seq <- seq(from = as.POSIXct("2014-05-01 00:00:00"),
to = as.POSIXct("2015-04-30 23:00:00"), by = "hour")
> df <- data.frame(date=time_seq)
> df
date
8013 2015-03-30 20:00:00
8014 2015-03-30 21:00:00
8015 2015-03-30 22:00:00
8016 2015-03-30 23:00:00
8017 2015-03-31 00:00:00
8018 2015-03-31 01:00:00
8019 2015-03-31 02:00:00
8020 2015-03-31 03:00:00
8021 2015-03-31 04:00:00
8022 2015-03-31 05:00:00
8023 2015-03-31 06:00:00
8024 2015-03-31 07:00:00
// merging with the original data
> a <- merge(data,df, x.by = data$date, y.by = df$date ,all=TRUE)
> a
date value
4005 2014-07-23 07:00:00 37003
4006 2014-07-23 07:30:00 NA
4007 2014-07-23 08:00:00 37216
4008 2014-07-23 08:30:00 NA
合并后我得到的值不正确,它们包含半小时值。解决这个问题的正确方法是什么?
当我的两个数据帧都是每小时一次时,为什么合并结果是以 30 分钟为间隔?
PS:我调查了这个问题:Fastest way for filling-in missing dates for data.table 并按照步骤操作,但没有帮助。
【问题讨论】:
-
你能
dput你的数据或其中的一部分吗?你的代码对我来说很好。 -
我导入了太多库,导致方法冲突。重新启动环境后,我的代码运行良好。感谢您的帮助!
标签: r datetime time-series missing-data