user1424739
user1424739

Reputation: 13655

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?

Upvotes: 2

Views: 78

Answers (3)

Onyambu
Onyambu

Reputation: 79208

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

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76402

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)

Upvotes: 1

stefan
stefan

Reputation: 123988

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

Upvotes: 1

Related Questions