Like so?
# Load libraries
library("tidyverse")
# Set seed for reproducibility
set.seed(182635)
# Define function for looking back 'size' positions in vector
which_max_in_window = function(x, size){
out = vector(mode = "numeric", length = length(x))
win = seq(1, size)
out[win] = which.max(x[win])
for( i in seq(size + 1, length(x)) ){
first = i - size + 1
last = i
win = seq(first, last)
out[i] = which.max(x[win]) + first - 1
}
return(out)
}
# Generate dummy data
n = 1000
d = tibble(Open = rnorm(n = n, mean = 100),
High = rnorm(n = n, mean = 100),
Low = rnorm(n = n, mean = 100),
Close = rnorm(n = n, mean = 100))
# Create new variable with max indices for previous 100 elements of Close vector
d = d %>% mutate(Serial = seq(1, nrow(.)),
Max_Val_Serial_No = which_max_in_window(x = Close, size = 100))
# Get tibble of top closing values in window
d_max = tibble(x = d %>% select(Max_Val_Serial_No) %>% distinct %>% pull,
y = d %>% select(Close) %>% slice(x) %>% pull)
# Visualise
d %>%
ggplot(aes(x = Serial, y = Close)) +
geom_line() +
geom_point(data = d_max, aes(x = x, y = y), inherit.aes = FALSE, pch = 'X',
size = 5, colour = "tomato") +
scale_x_continuous(breaks = seq(0, nrow(d), by = 100)) +
guides(colour = FALSE) +
theme_bw() +
ggtitle("Top Close Values Within Sliding Windows of size 100")
Please do run some tests, to see if you get the expected output - No guarantees given 