滑动windows:比较系列与所有系列before/after

Sliding windows: compare series with all series before/after

我对滚动还很陌生 windows。我正在计算一个函数,该函数比较数据中 window 与相同大小的所有 windows before/after 之间的相关性。假设没有间隙。我想使用一种整洁的方法,例如 tsibble and/or @Davis Vaughan slider

df <- structure(list(sales = c(2, 4, 6, 2, 8, 10, 9, 3, 5, 2), index = structure(c(1567123200, 1567209600, 1567296000, 1567382400, 1567468800, 1567555200, 1567641600, 1567728000, 1567814400, 1567900800), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, -10L), class = ("tbl_df", "tbl", "data.frame"))

假设我想计算系列前 3 天与之前所有 3 天之间的 Pearson 相关性 windows:

我们可以在删除前 3 行后为每 3 行创建一个 gl 的分组索引,然后在前 3 行和 [=21= 的每个块之间执行 cor ]

library(dplyr)
n <- 3
df %>%
    slice(-seq_len(n)) %>% 
    group_by(grp = as.integer(gl(n(), n, n()))) %>% 
    filter(n() == n) %>%
    summarise(cor = cor(df$sales[seq_len(n)], sales))

-输出

# A tibble: 2 x 2
#    grp    cor
#  <int>  <dbl>
#1     1  0.961
#2     2 -0.655

数据

df <- data.frame(sales = c(2, 4, 6, 2, 8, 10, 9, 3, 5, 2),
  index = seq(as.Date("2019-08-30"), length.out = 10, by = '1 day'))