split a time series data to windows of length 10. then for each window, find the closest 5 neighbors from past in r

main.r
# Assuming your time series data is in a vector or dataframe column called 'ts_data'

# Create a function to find the nearest neighbors for each window
find_neighbors <- function(x, past_data, k = 5) {
  # Calculate distance between window x and past_data
  dists <- dist(rbind(x, past_data))[-1,1]
  # Find the k closest neighbors
  closest_neighbors <- order(dists)[1:k]
  # Return the indices of the closest neighbors
  return(closest_neighbors)
}

# Create a list to store the windowed data
windowed_data <- list()

# Set window length to 10
window_length <- 10

# Loop over the time series data to create windows
for (i in 1:(length(ts_data) - window_length + 1)) {
  # Extract the window of length 10
  window <- ts_data[i:(i + window_length - 1)]
  # Add the window to the list
  windowed_data[[i]] <- window
  
  # Find the closest 5 neighbors from past for the current window
  if (i > 1) {
    # Extract past data up to the current window
    past_data <- ts_data[1:(i - 1)]
    # Find the nearest neighbors
    neighbors <- find_neighbors(window, past_data, k = 5)
    # Print the indices of the neighbors
    print(paste("Closest neighbors for window", i, ":", neighbors))
  }
}
1191 chars
36 lines

gistlibby LogSnag