繁体   English   中英

合并具有不同长度(间隔)的时间序列数据

[英]Merge time series data with different length (gaps)

我有两个水流量测量设备,每分钟都会给出一个值。 现在,我需要合并两个时间序列。 我的问题:设备每隔几个小时就会产生一些故障。 因此,两个时间序列具有不同的长度。 我需要先填补空白。 可以使用NA,零值或间隔前的前导值来完成此操作。

我可以通过时间序列的最小值和最大值轻松定义所需的时间向量tseq:

from <- as.POSIXct(min(Measurement1[[1]], Measurement1[[1]]))
to <- as.POSIXct(max(Measurement1[[1]], Measurement1[[1]]))
tseq <- as.data.frame(seq.POSIXt(from = from, to = to, by = deltaT, tz=UTC))

然后,我尝试使用Zoo函数完成两个列表Measurement1和Measurement2,如下所示:

Measurement1Zoo <- as.data.frame(zoo(x=Measurement1, tseq[[1]]))

这导致df的长度与tseq相同,但是zoo只是在向量的末尾添加了一些值。

我有点困惑动物园是如何工作的。 我只想在两个时间序列中添加缺少的时间戳,并用NA(或另一个值)完成它。 怎么办呢? 您可以在此处找到两个示例文件: 示例时间序列

谢谢!

您可以使用dplyr进行外部联接(即full_join):

library(data.table)
m1 <- fread(file = "/Measurement1.CSV", sep = ";", header = TRUE)
m1$Date <- as.POSIXct(m1$Date,format="%d.%m.%Y %H:%M",tz=Sys.timezone())

m2 <- fread(file = "/Measurement2.CSV", sep = ";", header = TRUE)
m2$Date <- as.POSIXct(m2$Date,format="%d.%m.%Y %H:%M",tz=Sys.timezone())
names(m2)[2] <- "Value 5"

min(m1$Date) == min(m2$Date) #TRUE
max(m1$Date) == max(m2$Date) #TRUE

library(dplyr)
m_all <- full_join(x = m1, y = m2, by = "Date")
nrow(m1)    #11517
nrow(m2)    #11520
nrow(m_all) #11520
head(m_all)

#                 Date Value 1 Value 2 Value 3 Value 4 Value 5
#1 2015-07-24 00:00:00      28       2       0      26      92
#2 2015-07-24 00:01:00      28       2       0      26      95
#3 2015-07-24 00:02:00      28       2       0      26      90
#4 2015-07-24 00:03:00      28       2       0      26      89
#5 2015-07-24 00:04:00      28       2       0      26      94
#6 2015-07-24 00:05:00      27       1       0      26      95

#checking NA's
sum(is.na(m1$`Value 1`)) #0
sum(is.na(m1$`Value 2`)) #0
sum(is.na(m1$`Value 3`)) #3
sum(is.na(m1$`Value 4`))#0
sum(is.na(m2$`Value 5`)) #42

sum(is.na(m_all$`Value 1`)) #3
sum(is.na(m_all$`Value 2`)) #3
sum(is.na(m_all$`Value 3`)) #6 
sum(is.na(m_all$`Value 4`)) #3
sum(is.na(m_all$`Value 5`)) #42

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM