Skip to content

Instantly share code, notes, and snippets.

@jrosell
Last active December 19, 2025 12:31
Show Gist options
  • Select an option

  • Save jrosell/a3d48b8fb1addf6d8c16b44ad2263c73 to your computer and use it in GitHub Desktop.

Select an option

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/
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