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 windowfind_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 neighborsreturn(closest_neighbors)
}
# Create a list to store the windowed datawindowed_data <- list()
# Set window length to 10window_length <- 10
# Loop over the time series data to create windowsfor (i in1:(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 windowif (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))
}
}