'How to nest a list of functions?

I have a list of functions.

fn=list(
  function(x) { ... }
  , function(x) { ... }
  , ...
)

I want to generate a nested function of these functions.

fn[[1]](fn[[2]](fn[[3]](...(fn[[m]](x))))) # Suppose there are m functions in the list.

Is there an easy way to composite these individual function as a nested function?

r


Solution 1:[1]

Another Base R approach:

fun <- function(x) Reduce(function(y, f)f(y), fn, init = x)
fun(1:10)
 [1]  3  4  5  6  7  8  9 10 11 12

Solution 2:[2]

With purrr::compose you could do:

fn <- list(function(x) x^2, sqrt, function(x) x + 2)

fn_compose <- purrr::compose(!!!fn)

fn_compose(c(1:10))
#>  [1]  3  4  5  6  7  8  9 10 11 12

Solution 3:[3]

In base R, use the accepted answer to this question.

composite <- function(f,g) function(...) f(g(...))
fn <- list(function(x) x^2, sqrt, function(x) x + 2)
f <- Reduce(composite, fn)

f(1:10)
#>  [1]  3  4  5  6  7  8  9 10 11 12

Created on 2022-04-17 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 stefan
Solution 3 Rui Barradas