【发布时间】:2021-03-08 20:08:26
【问题描述】:
假设我有两个不同长度的时间序列。两者都有time 和value 列。它们都在随机位置具有 NA 值。例如:
# Generate first series
series1 <- data.frame(
time = seq.POSIXt(
from = as.POSIXct("2020-01-01", origin = "1970-01-01"),
length.out = 100,
by = "1 day"
),
value = runif(100, min = 0, max = 100)
)
# Generate second series, which starts and ends and different times
series2 <- data.frame(
time = seq.POSIXt(
from = as.POSIXct("2019-12-01", origin = "1970-01-01"),
length.out = 80,
by = "1 day"
),
value = runif(80, min = 0, max = 100)
)
# Remove some values at random
random_idx1 <- sample(seq_len(nrow(series1)), 20)
random_idx2 <- sample(seq_len(nrow(series2)), 20)
series1$value[random_idx1] <- NA
series2$value[random_idx2] <- NA
太好了。如果我要确定每个系列的最大非 NA 序列,我可以使用stats::na.contiguous()。但是,一个系列的最长序列与另一个系列不同。
现在的问题是:如何确定两个系列之间最长的重叠非NA值序列?也就是说,两个时间序列之间时间匹配且不是 NA 值的最长值序列是什么?
【问题讨论】:
-
也许你想在“时间”之前加入他们
merge(series1, series2, by = 'time', all = TRUE) -
对,那么可以在合并帧上使用 na.contiguous 吗?
-
我正在尝试您的示例,但我没有找到两者共同的案例,即
full_join(series1, series2, by = 'time') %>% summarise(len1 = list(rle(!is.na(value.x) & !is.na(value.y))))。可能是因为您构建的示例不重叠 -
@akrun 我更新了示例。
标签: r dplyr data-science