Skip to content

Instantly share code, notes, and snippets.

@danlooo
Created November 8, 2021 08:32
Show Gist options
  • Save danlooo/9467cfde77fc59023317144002c87a13 to your computer and use it in GitHub Desktop.
Save danlooo/9467cfde77fc59023317144002c87a13 to your computer and use it in GitHub Desktop.
Compose a function multiple times to itself in R
l <- list(
list(
list(
a = 1
)
)
) %>%
enframe()
# How to simplify this repetetive code?
l %>%
unnest() %>%
unnest() %>%
unnest()
unnest(unnest(unnest(l)))
compose(!!!list(unnest, unnest, unnest))(l)
#' Compose a function multiple times to itself
#'
#' This function applies the function `fun` to the object `data` and then
#' applies the same function again to the result of this call until `n`
#' iterations are finished.
#'
#' add_one <- function(x) x + 1
#' add_one(add_one(add_one(2)))
#' compose_n(data = 2, n = 3, fun = "add_one")
#'
#' @param data the object to which the function should be appli
compose_n <- function(data, n = 1, fun = "identity") {
compose(!!!(map(rep(fun, n), match.fun)))(data)
}
l %>%
compose_n(3, "unnest")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment