Using map2 function to iterate values from dataframe

I'm learning R at the moment and discovered that I should use purrr functions instead of for loops.

I have a dataframe with column prices.

dataset <- data.frame( price =c(15.92, 15.86, 15.83, 15.79, 16.20, 15.99)

How perform the logical operation using map:
15.92 > max(15.86, 15.83, 15.79, 16.20, 15.99, 15.93)
15.86 > max(15.83, 15.79, 16.20, 15.99, 15.93)
15.83 > max(15.79, 16.20, 15.99, 15.93)
15.79 > max(16.20, 15.99, 15.93)
16.20 > max(15.99, 15.93)
15.99 > max(15.93)
15.93 > max(0)

And then print the numbers on the left and result on the right.

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

1 Like

Thank you so much this worked.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.