As you are dealing with sliding windows, this is more of a slider::slide()
than purrr::map()
task. Note that the max()
for empty vector is -Inf
not 0, for prices it should not matter, but it's something to be aware of.
library(dplyr)
library(slider)
dataset <- data.frame( price =c(15.92, 15.86, 15.83, 15.79, 16.20, 15.99, 15.93))
# to better illustrate slider behaviour, let's add `price_window` and `pw_max`columns
# .before = -1 : "look forward", i.e. exclude the current element from the window
# .after = Inf : select all elements after the current element
dataset |>
mutate(price_window = slide_chr(price, paste0, collapse =", ", .before = -1, .after = Inf),
pw_max = slide_dbl(price, max, .before = -1, .after = Inf),
result = price > slide_dbl(price, max, .before = -1, .after = Inf))
#> Warning: There were 2 warnings in `mutate()`.
#> The first warning was:
#> ℹ In argument: `pw_max = slide_dbl(price, max, .before = -1, .after = Inf)`.
#> Caused by warning in `.f()`:
#> ! no non-missing arguments to max; returning -Inf
#> ℹ Run `dplyr::last_dplyr_warnings()` to see the 1 remaining warning.
#> price price_window pw_max result
#> 1 15.92 15.86, 15.83, 15.79, 16.2, 15.99, 15.93 16.20 FALSE
#> 2 15.86 15.83, 15.79, 16.2, 15.99, 15.93 16.20 FALSE
#> 3 15.83 15.79, 16.2, 15.99, 15.93 16.20 FALSE
#> 4 15.79 16.2, 15.99, 15.93 16.20 FALSE
#> 5 16.20 15.99, 15.93 15.99 TRUE
#> 6 15.99 15.93 15.93 TRUE
#> 7 15.93 -Inf TRUE
Created on 2024-01-30 with reprex v2.0.2