get two time series. split them into intersecting windows of length 10. then find the closest 5 neighbors for one time series from the other time series in r

To split two time series into intersecting windows of length 10, you can use the slider package in R. Here's an example of how to do it:

library(slider)

# example time series
ts1 <- ts(rnorm(100), frequency = 1)
ts2 <- ts(rnorm(100), frequency = 1)

# define window size and overlap
win_size <- 10
overlap <- 5

# define custom function to split time series into windows
split_ts <- function(x) {
  slider::slide(x, width = win_size, by = overlap, keep = c(win_size, 1))
}

# create intersecting windows
windows1 <- split_ts(ts1)
windows2 <- split_ts(ts2)

# combine windows into a data frame
windows <- data.frame(id = 1:length(windows1),
                      ts1 = windows1,
                      ts2 = windows2)
580 chars
24 lines

Next, to find the 5 closest neighbors for one time series from the other time series, you can use the dist() function in R to calculate the distance between each window of the two time series. Here's an example of how to do it:

# calculate distance matrix
dist_matrix <- dist(windows[, 2:3])

# loop over each row of the distance matrix
neighbors <- list()
for (i in 1:nrow(dist_matrix)) {
  # find indices of the 5 closest neighbors
  indices <- order(dist_matrix[i, ])[1:5]
  # store indices in list
  neighbors[[i]] <- indices
}

# add neighbors to windows data frame
windows$neighbors <- neighbors
374 chars
15 lines

This will give you a data frame with the intersecting windows of the two time series, along with the 5 closest neighbors in the other time series for each window.

gistlibby LogSnag