我正在处理一个包含每小时数据的时间序列数据集 . 数据包含一些缺失值,因此我尝试使用正确的时间值创建数据帧(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并按照步骤进行,但没有帮助 .