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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With