Last active
December 19, 2025 12:31
-
-
Save jrosell/a3d48b8fb1addf6d8c16b44ad2263c73 to your computer and use it in GitHub Desktop.
Reduce loops using purrr base R pipe. Inspired by https://masalmon.eu/2023/07/26/reduce/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(purrr) | |
| # The intial information | |
| elements <- tibble::tribble( | |
| ~key , ~values , | |
| "Barbie" , "shoes" , | |
| "Oppenheimer" , "history" | |
| ) | |
| # Aditional values we want to proces | |
| additional_values <- list( | |
| list(key = "Barbie", values = "sparkles"), | |
| list(key = "Barbie", values = "feminism"), | |
| list(key = "Oppenheimer", values = "fire") | |
| ) | |
| # Function to process each value to a single value | |
| reduce_values <- \(value, next_value) { | |
| value[value[["key"]] == next_value[["key"]], ][["values"]] <- | |
| toString(c( | |
| value[value[["key"]] == next_value[["key"]], ][["values"]], | |
| value[["values"]] | |
| )) | |
| value | |
| } | |
| # Adding the aditional values to the elements table | |
| elements |> | |
| purrr::reduce(.x = additional_values, .f = reduce_values, .init = _) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment