Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compose a list of functions

Tags:

r

For example, I have a vector of functions: fun_vec <- c(step1,step2,step3). Now I want to compose them like this: step1(step2(step3(x))). How do I do this using fun_vec? (Suppose that fun_vec isn't fixed and can have more or less functions.)

like image 636
Catiger3331 Avatar asked Oct 23 '18 18:10

Catiger3331


Video Answer


1 Answers

Similar to Frank's use of freduce, you can use Reduce:

step1 <- function(a) a^2
step2 <- function(a) sum(a)
step3 <- function(a) sqrt(a)
steps <- list(step1, step2, step3)
Reduce(function(a,f) f(a), steps, 1:3)
# [1] 3.741657
step3(step2(step1(1:3)))
# [1] 3.741657

You can see it "in action" with:

Reduce(function(a,f) f(a), steps, 1:3, accumulate=TRUE)
# [[1]]
# [1] 1 2 3
# [[2]]
# [1] 1 4 9
# [[3]]
# [1] 14
# [[4]]
# [1] 3.741657
like image 133
r2evans Avatar answered Nov 01 '22 04:11

r2evans